A method and system for generating a vehicle fleet report dynamically based on natural language intent analysis
Patent Information
- Application Number
- CN202610756805.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-05-29
- Publication Date
- 2026-08-18
AI Technical Summary
[0010]本发明的目的是为了以解决现有技术中自然语言生成报表查询时所面临的安全不可控、逻辑不可验证、领域适配差、语义歧义无法消解等问题
[0022](1) Secure and verifiable compilation architecture and two-way closed-loop feedback: By introducing a compilation verification layer and a two-level closed-loop feedback mechanism, each query transformation generates an auditable intermediate representation (structured intent JSON and intermediate AST). When compilation verification fails, the correction process is automatically triggered through the first-level closed-loop feedback, rather than simply reporting an error; when the cache expires, it is automatically recompiled through the second-level closed-loop feedback. Compared with direct black-box generation of SQL or template matching followed by auditing, this invention provides a formal verification path and an automatic error recovery mechanism at compile time, realizing a dual transformation from post-audit to compile-time verification + closed-loop correction. Comparative testing has verified that the semantic error (illegal aggregation/type mismatch) blocking rate of this invention reaches 100%, while the general NL2SQL solution is only about 12%.
Smart Images

Figure CN122594367A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of vehicle network data processing and SaaS platform architecture technology, and in particular to a method and system for dynamically generating fleet reports based on natural language intent parsing. Background Technology
[0002] Currently, fleet management platforms typically offer data reporting functionality to display business data such as vehicle trajectories, fuel consumption statistics, and maintenance information. Existing reporting systems mainly employ a hard-coded architecture (fixed front-end view components + pre-defined back-end SQL query interfaces). In recent years, some solutions based on Natural Language to SQL (NL2SQL) have emerged, attempting to directly convert user queries into SQL queries using large language models.
[0003] For example, the publicly available NL2SQL report generation solution (publication number CN120596499A, application date May 2025) adopts a matching architecture of (scenario SQL template library + scenario prompt dictionary). This means that SQL templates are pre-built for each business scenario, and the corresponding template is matched based on the natural language query intent before parameters are filled in to generate SQL. The generated SQL is then reviewed. However, this solution's validation is limited to the legality of SQL syntax and cannot detect semantic type mismatches (such as performing numerical aggregation on text fields) or illegal aggregation operations. Furthermore, it does not address data isolation mechanisms in multi-tenant SaaS environments. In addition, this solution relies on a predefined template library; for query requirements not covered by the template library, the system cannot respond, and its scalability is limited by the completeness of the templates.
[0004] The general-purpose large language model NL2SQL solution also has fundamental flaws: (1) Unverifiability: The SQL logic generated by the large language model cannot be formally verified. The correctness of field mapping and aggregation operations depends on the black box of the model and lacks an auditable intermediate representation. Although the template matching scheme outputs deterministic SQL, the template library construction cost is high and it cannot handle complex queries that are not predefined.
[0005] (2) Security vulnerability: In a multi-tenant environment, if the SQL generated by the model does not include tenant filtering conditions, or if a user attempts to query across tenants through keyword injection, the system cannot effectively block it. The existing solution only performs log auditing after SQL execution, which is (post-event auditing) and cannot prevent privilege escalation at compile time.
[0006] (3) Poor domain adaptability: There is a lack of explicit modeling of fleet business terms (such as fuel consumption per 100 kilometers, refrigerated truck) and business rules (such as enumeration value constraints), resulting in a high probability of generating erroneous SQL.
[0007] (4) Unable to guarantee determinism and reproducibility: The same input may generate different SQL at different times, resulting in inconsistent report results, which does not meet the requirements of enterprise-level audit.
[0008] (5) Semantic ambiguity cannot be resolved: When users use colloquial terms (such as fuel consumption), the model may be randomly mapped to different physical fields and cannot be confirmed by interacting with the user.
[0009] The root cause of the above problems lies in the fact that existing solutions (including template matching and general NL2SQL) only use the large language model as a SQL generator, without building a verifiable, injection-safe, and interactive disambiguation-enabled compilation intermediate layer. Furthermore, existing solutions lack a closed-loop mechanism for feeding back compilation verification results to intent generation, failing to automatically trigger a correction process when errors are detected. Therefore, a technical solution that can address these core issues through a multi-level closed-loop feedback architecture is urgently needed. Summary of the Invention
[0010] The purpose of this invention is to solve the problems faced by existing technologies in generating reports and queries using natural language, such as uncontrollable security, unverifiable logic, poor domain adaptability, and unresolved semantic ambiguity. To achieve the above objective, this invention adopts the following technical solution: A method for dynamically generating fleet reports based on natural language intent parsing includes the following steps: S1: Configure and store the metadata dictionary, which consists of multiple field entries. Each field entry contains three core attributes: physical field name (fieldname), data type (datatype), and allowed aggregation functions (allowedaggregations). Using the fleet business data table structure as input, configure and store the fleet business metadata dictionary; Furthermore, each field entry can also include the following extended attributes: Chinese tag `displayname`, a list of valid values `enumvalues` when `datatype` is `enum`, `isgroupable` indicating whether it is allowed as a grouping field, and a list of semantic aliases `semanticiases`. Simultaneously, the system calculates the hash value `metahash=MD5` (the canonical string defined for all fields) of the current metadata dictionary content for cache consistency verification.
[0011] As the rule base of the compilation chain, the construction of prompt words in S3 and the compilation verification in S4 both rely on the metadata dictionary content output by S1. The cache verification in S5 relies on the version hash output by S1. The metadata dictionary output by S1 defines the entire legal operation space of the compilation chain and is the source of constraints for all subsequent steps.
[0012] S2: Using the metadata dictionary as the constraint domain, receive the user's natural language report request and preprocess it into standard query text, including parsing relative time into absolute time interval; Furthermore, the user's natural language report request includes voice or text form, and the preprocessing includes speech recognition and transcription, spelling correction, sentence standardization, and parsing of relative time expressions (such as the most recent week) into absolute time intervals.
[0013] S3: Using the standard query text as input, generate a structured intent JSON through the large language model, subject to the field set and allowed operation constraints defined by the metadata dictionary. The structured intent JSON includes the fields to be displayed, filtering conditions, grouping dimensions, chart type, and time range. Furthermore, the field set refers to the collection of all physical field names in the metadata dictionary (such as region, fuel100km, vehicletype, etc.), and the large language model can only select fields from this set. "Allowed operation constraints" refer to the list of allowed aggregations defined for each field in the metadata dictionary (e.g., fuel100km only allows avg / sum / max / min), and the aggregation operations used by the large language model for this field must belong to this list.
[0014] The specific method for generating structured intent JSON is as follows: The system constructs a prompt word template, which formats all field entries in the metadata dictionary into a field constraint list (listing the physical field name, data type, allowed aggregations, semantic aliases, etc. of each field in structured text), along with system role instructions (requiring the model to select fields only from the list and that aggregation operations must not exceed the list definition) and a predefined JSON Schema (specifying that the output must include selectfields, where conditions, group by, charttype, and timerange). This prompt word is passed to the large language model via API calls. The model's output space is restricted to the range of the constraint list and Schema definition, thereby generating a compliant structured intent JSON. If the model output does not conform to the JSON Schema (e.g., field names are not in the list, aggregation functions are not allowed, or the format is incorrect), the system automatically triggers a retry mechanism: after supplementing the format correction instructions, the model is called again until the output is valid.
[0015] After generating the structured intent JSON, the system further performs post-processing based on the semanticiases in the metadata dictionary: mapping colloquial field names in the JSON to standard physical field names. If multiple matching candidates are found during the mapping process (e.g., "fuel consumption" matches both fuel100km and oillevel), the intent clarification and rollback process in the first-level closed-loop feedback is triggered: the candidate field list is returned to the user, the structured intent JSON is corrected after receiving the user's selection, and then it enters the S4 compilation and verification process.
[0016] The large language model is a large-scale language model with function call capability or structured JSON output capability. Specifically, it can be a model with equivalent natural language understanding and structured output capabilities, such as GPT-4, Claude, Wenxin Yiyan, or Tongyi Qianwen. The large language model is connected to the system through an API interface call. The system injects metadata dictionary constraints into the model's context window through preset prompt word templates and constrains the model's output format to a structured object that strictly conforms to the predetermined JSON Schema. If the model output does not meet the format requirements of the structured JSON, the system automatically triggers a retry mechanism, calling the model again with supplementary format correction instructions until the output is valid.
[0017] Furthermore, the Schema definition of the structured intent JSON is as follows: selectfields is an array of fields to be displayed, each element of which is a JSON object containing field (physical field name), alias (Chinese field label), aggregation (aggregation operation, null indicates no aggregation, the value must be any value in the allowed list of the field in the metadata dictionary); whereconditions is an array of filtering conditions, each element containing field (physical field name), operator (operator, the value can be one of eq, neq, gt, gte, lt, lte, in, like, between), and value (filter value); Group By is an array of grouping dimensions, the elements of which must be the field values corresponding to the fields in selectfields where aggregation is null; charttype is the chart type, the value can be one of bar (bar chart), line (line chart), pie (pie chart), table (table), scatter (scatter plot); timerange is a time range object containing two fields: start (start timestamp, ISO8601 format) and end (end timestamp, ISO8601 format).
[0018] S4: Using the structured intent JSON as input, perform compilation verification through the AST compiler. After the compilation verification is successful, an intermediate AST is generated. When the intermediate AST is converted into a secure SQL statement, the tenant isolation condition of the current user is forcibly attached inside the code generation function of the AST compiler. The compilation verification includes: checking whether each field exists in the metadata dictionary, checking whether the aggregation operation belongs to the allowed set of the field, checking the matching of the operator and the data type, and checking whether the non-aggregate Select field appears in Group By; Furthermore, S4 takes the structured intent JSON output by S3 and the metadata dictionary output by S1 as input and performs the following sub-steps: S41: Parse the structured intent JSON to construct abstract syntax tree nodes; S42: Traverse each field, look up the type definition and allowed operations in the metadata dictionary, and perform static type checking and aggregation validity verification; S43: Check the semantic consistency between Group By and SelectFields. If a non-aggregate Select field does not appear in Group By, a compilation error will occur. S44: Check the match between the operator and the field type in the Where condition, and verify whether the enumeration value is in the list of valid values; S45: After the verification passes, an intermediate AST is generated. When converting the AST into an SQL statement, the tenant isolation condition of the current user (tenantid=current tenant) is forcibly attached inside the code generation function of the AST compiler, and a safe SQL statement is output. S46: If errors such as field non-existence, illegal aggregation, type mismatch, or semantic ambiguity are detected during the compilation and verification process, the current compilation process is blocked, triggering the first-level closed-loop feedback—that is, returning error messages and candidate correction options to the user, receiving the user's selection or correction, feeding back the corrected intent request to S3 to regenerate the structured intent JSON, and re-executing the compilation and verification process from S41 to S46.
[0019] S4 is the core security valve and verification center of the entire chain. S4 transforms the non-deterministic output of the large language model into a deterministic, auditable intermediate representation (AST), achieving the shift from post-audit to compile-time verification through a compile-time formal verification path. Simultaneously, S4 acts as the trigger for the first-level closed-loop feedback, driving intent regeneration when an error is detected. The mandatory tenant isolation injection logic in S4 resides within the AST compiler, independent of upper-level input content, ensuring that the security mechanism cannot be bypassed. The secure SQL statements output by S4 are the direct input to S5 execution, and their determinism is guaranteed by compile-time verification—the same structured intent JSON and the same metadata dictionary always output the same SQL.
[0020] S5: Execute the secure SQL statement to obtain the result set, dynamically render the report according to the chart type information in the structured intent JSON, and output the final report; S5 takes the secure SQL statement output by S4 as input, executes the SQL to obtain the result set, dynamically renders the chart report based on the chart type information in the structured intent JSON generated by S3, and outputs the final report. When the user saves the report, the structured intent JSON is serialized into an XML configuration file, appending the metadata dictionary version hash (metahash) and relative time expression output by S1. When the user triggers the report again, the second-level closed-loop feedback logic is executed, specifically including: S51: Verify whether the metaahash in the XML configuration file is consistent with the metaahash in the current metadata dictionary; S52: If the hash is consistent and the absolute time interval has not expired, the structured intent JSON in the XML is directly used to enter the S4 compilation and execution, skipping the large language model call in S3, thus reducing the computing power overhead. S53: If the hash is inconsistent, it means that the metadata dictionary has been changed (such as adding or deleting fields or modifying types). Discard the XML configuration and feed back the trigger signal to S3 to regenerate the structured intent JSON and recompile and execute it. S54: If the hash is consistent but the absolute time has expired (e.g., the time interval corresponding to the most recent week has shifted), then only update the absolute time interval in the XML, keep the structured JSON structure unchanged, and re-enter S4 for compilation and execution.
[0021] S5 serves as the final presentation layer for reports and the secondary trigger for closed-loop feedback. S5 maintains cache consistency through metadata version hash verification and automatically adapts to metadata dictionary changes via the second-level closed-loop feedback mechanism, preventing erroneous reports caused by outdated configurations. The logical retention strategy using relative time expressions maximizes cache hit rate and reduces the cost of repeated calls to large language models. Beneficial effects
[0022] (1) Secure and verifiable compilation architecture and two-way closed-loop feedback: By introducing a compilation verification layer and a two-level closed-loop feedback mechanism, each query transformation generates an auditable intermediate representation (structured intent JSON and intermediate AST). When compilation verification fails, the correction process is automatically triggered through the first-level closed-loop feedback, rather than simply reporting an error; when the cache expires, it is automatically recompiled through the second-level closed-loop feedback. Compared with direct black-box generation of SQL or template matching followed by auditing, this invention provides a formal verification path and an automatic error recovery mechanism at compile time, realizing a dual transformation from post-audit to compile-time verification + closed-loop correction. Comparative testing has verified that the semantic error (illegal aggregation / type mismatch) blocking rate of this invention reaches 100%, while the general NL2SQL solution is only about 12%.
[0023] (2) Mandatory tenant isolation to fundamentally prevent unauthorized access: Traditional solutions append tenant isolation conditions after SQL generation, which carries the risk of omissions or being bypassed by prompts. This invention forcibly injects tenant isolation conditions at the final stage of S4's AST compilation. The injection logic resides within the AST compiler and is unaffected by upper-layer natural language content and structured intent JSON content. Even if the large language model outputs an empty Where condition, the AST compiler's code generation function still unconditionally appends the tenantid condition; the injected tenantid originates from the server-side session authentication context, not from user input. After testing with 10 deliberately constructed cross-tenant queries, this solution achieved a 100% blocking rate, while the baseline solution relying on post-filtering only achieved approximately 62%.
[0024] (3) Metadata dictionary-driven deterministic verification: The output of the large language model is restricted to a finite set of dictionary definitions. After static type checking and aggregation validity verification by the AST compiler, the final generated SQL is deterministic—the same input and the same metadata dictionary will always output the same SQL. Comparative tests show that the success rate of generating correct SQL in the first round of this invention reaches 92%, while the general NL2SQL solution only has about 47%.
[0025] (4) Semantic alias mapping and first-level closed-loop feedback work together to disambiguate: By explicitly modeling the equivalence relations of domain terms through semantic aliases, user colloquial expressions are deterministically mapped to physical fields, eliminating the ambiguity of the model black box. When field ambiguity or semantic errors are automatically detected, the first-level closed-loop feedback drives the system to interact with the user for clarification, rather than directly reporting errors or generating erroneous SQL, forming a complete closed loop of automatic error detection - human-computer interaction correction - recompilation.
[0026] (5) Cache version consistency and second-level closed-loop feedback work together to ensure consistency: The XML cache carries metadata version hashes. After a field changes, it is automatically invalidated and recompiled through the second-level closed-loop feedback, avoiding errors caused by outdated configurations. At the same time, relative time expressions are retained as logical expressions, so that the cache does not become invalid over time, maximizing the cache hit rate and reducing computing power overhead. Attached Figure Description
[0027] Figure 1 A flowchart illustrating the overall process of a method for dynamically generating fleet reports based on natural language intent parsing, as provided in this embodiment of the invention. Figure 2 This is a schematic diagram of the system module structure provided in an embodiment of the present invention; Figure 3 This is a sequence diagram illustrating the logical interactions of structured query intent object validation, compilation, and report rendering persistence provided in this embodiment of the invention. Detailed Implementation
[0028] To provide a further understanding of the purpose, structure, features, and functions of the present invention, detailed descriptions are provided below with reference to specific embodiments. Embodiment 1 This embodiment provides a method for dynamically generating fleet reports based on natural language intent parsing, deployed in a multi-tenant SaaS-based fleet management platform. The fleet management platform manages vehicle data from multiple independent fleets, each fleet being an independent tenant with its own metadata dictionary view. The following details the specific steps: S1: Using the fleet business data table structure as input, configure and store a metadata dictionary. The metadata dictionary consists of multiple field entries, each of which contains a physical field name (field). name , such as fuel 100km Used for subsequent SQL generation, data type data type This determines the types of comparison operators and aggregate functions that can be used. For example, date... time The type supports the `between` operation; the `enum` type only supports `eq`, `neq`, and `in`, and the list of allowed aggregate functions is `allowed`. aggregations Limit the aggregation operations that the model can perform on this field. For example, fuel. 100km Allow avg, sum, max, and min, but not count (meaningless); region does not allow any aggregation, can only be used for grouping or filtering; Furthermore, each field entry may also include the following extended attributes: Chinese tag display name Use a user-friendly name for report display, such as "fuel consumption per 100 kilometers"; when data type List of valid values for enumvalues Is group allowed as a grouping field? able Semantic alias list aliases Simultaneously, the system calculates the hash value of the current metadata dictionary content. hash =MD5(canonical string of all field definitions), where the "canonical string" is the MD5 hash of all field definitions (sorted by field name, concatenated with field name, type, allowed aggregation list, enumeration value list, semantic alias, etc.) after being concatenated into a long string. This hash value is stored in the server cache and used for cache consistency verification (second-level closed-loop feedback) in S5.
[0029] The metadata dictionary configured in S1 is the unique and irreplaceable rule base of the entire compilation chain: it provides the legal set of fields and operation boundaries for the S3 large language model (eliminating illusions), provides the sole basis for the four checkpoints of field existence, aggregation legality, etc. for S4 compilation verification, and supports the second-level closed-loop feedback cache consistency verification of S5 through version hashing - once the dictionary changes, the cache is automatically invalidated and recompilation is triggered, thereby transforming nondeterministic natural language queries into a deterministic finite operation space. It is the core cornerstone for realizing a verifiable compilation architecture.
[0030] S2: Using the metadata dictionary as the constraint domain, receive the user's natural language report request and preprocess it into standard query text, including parsing relative time into absolute time interval; In this embodiment, the user speaks a natural language request through the voice input interface of the fleet management platform: "Average fuel consumption per 100 kilometers for refrigerated trucks in each region over the past week." S2 first calls the voice recognition service to transcribe the speech into the text string "Average fuel consumption per 100 kilometers for refrigerated trucks in each region over the past week." Then, spell correction (there are no typos in this sentence) and sentence standardization are performed, unifying "each region" to "grouped by region," resulting in the standard query text: "Statistics on the average fuel consumption per 100 kilometers for refrigerated trucks grouped by region over the past week." Finally, S2 parses the relative time expression "past week": using the current system date (assumed to be 2025-01-15) as a reference, "past week" is converted into an absolute time interval start=2025-01-08 00:00:00, end=2025-01-15 23:59:59. This standard query text, along with the parsed absolute time interval, is output to S3. The above preprocessing process always uses the metadata dictionary defined by S1 as the constraint domain—for example, the fields region and fuel defined in the dictionary. 100km vehicle typeThe data type of the time field determines the format and validity of the value when S3 generates the structured intent. However, S2 itself does not modify or interpret the dictionary content. It is only responsible for converting the user's natural language into structured text that can be input by S3, while eliminating ambiguity in the expression of time.
[0031] S3: Using the standard query text as input, generate a structured intent JSON through the large language model, subject to the field set and allowed operation constraints defined by the metadata dictionary. The structured intent JSON includes the fields to be displayed, filtering conditions, grouping dimensions, chart type, and time range. Furthermore, the field set refers to the collection of all physical field names in the metadata dictionary (such as region, fuel). 100km vehicle type (etc.), the large language model can only select fields from this set. The allowed operation constraints refer to the allowed parameters defined in the metadata dictionary for each field. aggregations List (e.g., fuel) 100km Only avg / sum / max / min are allowed; the aggregation operation used by the large language model on this field must belong to this list.
[0032] The specific method for generating structured intent JSON is as follows: the system constructs a prompt word template, which formats all field entries in the metadata dictionary into a list of field constraints. Below is a simplified example of a prompt word template: System Role: You are a fleet report intent parsing assistant, and you must strictly adhere to the following constraints when outputting JSON.
[0033] List of field constraints: Field name: region, Data type: string, Aggregation allowed: null, Semantic alias: ["Region", "Region"] Field name: fuel 100km Data type: numeric, Aggregation allowed: ["avg","sum","max","min"], Semantic alias: ["Fuel consumption per 100 kilometers","Fuel consumption"]; Field name: vehicle type Data type: enum, allowed aggregation: null, valid values: ["refrigerated truck", "ordinary truck", "hazardous goods truck"]; Field name: time stamp Data type: date time Aggregation is allowed: null (JSON Schema). Output must include: select. fields(Array, each element contains field, alias, aggregation), WHERE condition (array, each element contains field, operator, value), GROUP BY (array), chart type (string), time range (The object contains start and end); User question: {Insert standard query text here}; The prompt word is passed to a large language model (such as GPT-4, Wenxin Yiyan, or Tongyi Qianwen, the specific model can be configured according to the deployment environment) via API calls. The model's output space is restricted to the scope of the constraint list and schema definition, thereby generating a compliant structured intent JSON. If the model output does not conform to the JSON schema (e.g., field names are not in the list, aggregate functions are not allowed, or the format is incorrect), the system automatically triggers a retry mechanism: after supplementing the format correction instructions, the model is called again until the output is valid. Through the above prompt word project, this invention transforms the nondeterministic output of the large language model into a finite operation space limited by the metadata dictionary, ensuring the verifiability of subsequent compilation and verification.
[0034] S4: Using the structured intent JSON as input, perform compilation verification through the AST compiler. After the compilation verification is successful, an intermediate AST is generated. When the intermediate AST is converted into a secure SQL statement, the tenant isolation condition of the current user is forcibly attached inside the code generation function of the AST compiler. The compilation verification includes: checking whether each field exists in the metadata dictionary, checking whether the aggregation operation belongs to the allowed set of the field, checking the matching of the operator and the data type, and checking whether the non-aggregate Select field appears in Group By; Furthermore, S4 takes the structured intent JSON output by S3 and the metadata dictionary output by S1 as input and performs the following sub-steps: S41: Parse the structured intent JSON to construct abstract syntax tree nodes; After receiving the structured intent JSON, the system begins reading it item by item. The so-called "constructing abstract syntax tree nodes" means converting each intent segment in the JSON into an in-memory object that can subsequently generate SQL. Specifically, the process is as follows: Read select fields Array: Each item generates an "output field object" that records the field name, alias, and whether it is aggregated. In this example, the first object: field region, alias region, no aggregation; the second object: field fuel. 100km , also known as average fuel consumption per 100 kilometers, aggregated operation is avg.
[0035] Reading the WHERE condition array: Each item generates a "condition object," recording the fields, operators, and comparison values. In this example, one object is generated: field vehicle_type, operator eq, and value refrigerated vehicle.
[0036] Read the Group By array: Generate a "grouping object" that records the list of fields to be grouped: ["region"].
[0037] Read time range Object: The system automatically converts it into another condition object: the time field. stamp The `between` operator takes `start` and `end` as the start and end values, respectively. This condition is added to the preceding condition list.
[0038] Data table name (e.g., vehicle) status The JSON is pre-configured by the system and does not come from the user; it directly generates a "table object".
[0039] These objects (output fields, conditions, groups, tables) are the nodes of the AST. They are currently just a few independent objects in memory, and we need to check their validity next.
[0040] S42: Traverse each field, look up the type definition and allowed operations in the metadata dictionary, and perform static type checking and aggregation validity verification; The system takes the field names (region, fuel) from each object 100km vehicle type time stamp Check the S1 metadata dictionary to confirm that all entries exist. Also check the aggregation: fuel. 100km The aggregation is avg, and the dictionary allows avg, sum, max, and min for this field, so there's no problem. The region field has no aggregation (null), which is also allowed. Other fields do not involve aggregation, so we skip them.
[0041] S43: Check Group By and Select Fields To ensure semantic consistency, a compilation error will occur if a non-aggregate Select field does not appear in Group By. The system selects all fieldsFind the fields where `aggregation` is null; these are ordinary fields that are not aggregated. According to SQL rules, ordinary fields must appear in the `GROUP BY` clause; otherwise, the query is meaningless. In this example, the only ordinary field is `region`, and the `GROUP BY` clause contains `["region"]`, so the check passes. If the user wants to display both `region` and `vehicle`, this will be necessary. type However, if only "["region"] is specified in Group By, then the vehicle... type This will trigger an error, and the system will display the message "non-aggregate field vehicle". type "Not appearing in the group list", and compilation is blocked.
[0042] S44: Check the match between the operator and the field type in the Where condition, and verify whether the enumeration value is in the list of valid values; The specific rules for "checking operator matching with data type" in S44 are as follows: For numeric fields, allowed operators include eq (equal to), neq (not equal to), gt (greater than), gte (greater than or equal to), lt (less than), lte (less than or equal to), and between (range), supporting equality and range comparisons; for time fields, allowed operators include eq, between, gt, gte, lt, and lte, used for precise time matching or time range queries; for string fields, allowed operators include eq, neq, and like, where like is used for fuzzy matching; for enumeration fields, only eq, neq, and in operators are allowed, supporting only equality and set comparisons. If the operator does not match the field type, for example, using the gt operator on a string field, a compilation error will occur and the first level of closed-loop feedback will be triggered. Furthermore, for enumeration fields, the system will further check whether the value in the Where condition is in the predefined list of valid values in the metadata dictionary; if not, a compilation error will also occur and the first level of closed-loop feedback will be triggered.
[0043] S45: After successful validation, an intermediate AST is generated. When converting the AST into SQL statements, the current user's tenant isolation condition is forcibly appended within the code generation function of the AST compiler. id =Current tenant), output secure SQL statement; After all checks pass, the system begins generating SQL. When generating the WHERE clause, the code generation function unconditionally adds a condition: tenant. id =The tenant ID of the currently logged-in user. This tenant ID is read directly from the server-side session context, such as team. A Users cannot modify or bypass this through any input. Even the original where...conditions Even if it's empty, this condition will still be added.
[0044] S46: If errors such as field non-existence, illegal aggregation, type mismatch, or semantic ambiguity are detected during the compilation and verification process, the current compilation process is blocked, triggering the first-level closed-loop feedback—that is, returning error messages and candidate correction options to the user, receiving the user's selection or correction, feeding back the corrected intent request to S3 to regenerate the structured intent JSON, and re-executing the compilation and verification process from S41 to S46.
[0045] Suppose that in S42, the system detects select fields There is a field called "oil". level However, this field is not found in the metadata dictionary. The system will immediately stop compiling and return a message to the user: "Field oil..." level It doesn't exist. Do you want to use fuel? 100km (Fuel consumption per 100 kilometers)? Users can choose to confirm the replacement or manually enter other fields. After user confirmation, the system will output the modified structured intent JSON (containing oil...) level Change to fuel 100km The data is sent back to S3, requesting the large language model to regenerate the complete intent JSON. The new JSON will then re-enter the compilation and verification process in S41-S46. If it passes this time, the process continues; if there are still problems, the closed loop is triggered again until verification passes or the user actively abandons the process. This forms a closed loop of "compilation and verification → error feedback → regeneration of intent → re-verification," ensuring that the intent ultimately enters the SQL generation process. Figure 1 It must be legal.
[0046] S5: Execute the secure SQL statement to obtain the result set, dynamically render the report according to the chart type information in the structured intent JSON, and output the final report; S5 takes the secure SQL statement output by S4 as input, executes the SQL to obtain the result set, dynamically renders the chart report based on the chart type information in the structured intent JSON generated by S3, and outputs the final report. When the user saves the report, the structured intent JSON is serialized into an XML configuration file, and the metadata dictionary version hash output by S1 is appended. hash And a relative time expression; when the user triggers the report again, the second-level closed-loop feedback logic is executed, specifically including: S51: Validate the meta tags in the XML configuration file hash Meta with the current metadata dictionary hash Are they consistent? After some time, the user clicked on the saved report again, wanting to view the latest "average fuel consumption per 100 kilometers for refrigerated trucks in various regions over the past week." The system first located the previously saved XML file and read the meta data within it. hash Then, the meta-values recalculated from the current metadata dictionary in S1 are compared with the metadata in S1. hash Compare the two hash values. They may be the same or different.
[0047] S52: If the hash is consistent and the absolute time interval has not expired, the structured intent JSON in the XML is directly used to enter the S4 compilation and execution, skipping the large language model call in S3, thus reducing the computing power overhead. If the hashes match, it means the metadata dictionary hasn't changed (no fields added or removed, no data type changed, no enumeration values changed). The system also checks: if the last save used an absolute time range (e.g., 2025-01-08 to 2025-01-15), that period has now passed, but the XML still retains the relative time expression "last week". The system finds the absolute time has expired, so this condition is not met, and S52 won't be executed. If the user repeatedly queries within the same day (e.g., queried and saved in the morning, then opened it again in the afternoon), the absolute time range hasn't expired. In this case, the system directly retrieves the structured intent JSON stored in the XML, skips the large model call in S3, and directly sends it to S4 for compilation and execution. This saves the computational power and time of one large model call.
[0048] S53: If the hash is inconsistent, it means that the metadata dictionary has been changed (such as adding or deleting fields or modifying types). Discard the XML configuration and feed back the trigger signal to S3 to regenerate the structured intent JSON and recompile and execute it. If the hashes are inconsistent, for example, if the administrator changes the fuel in the background... 100km The field was changed to fuel_consumption_per_100km, or vehicle was deleted. type If a certain enumeration value is specified, then the field names or constraints in the old XML may be outdated. The system will discard this XML configuration and trigger a second-level closed-loop feedback: prompting the user that "the data dictionary corresponding to the report has been updated and is being regenerated...", and then sending the original query intent (such as "the average fuel consumption per 100 kilometers of refrigerated trucks in various regions in the past week") back to S3, allowing the large language model to regenerate the structured intent JSON, and then proceeding to S4 for compilation and execution and S5 for rendering. This ensures that the report is always based on the latest dictionary definition and will not fail due to outdated caching.
[0049] S54: If the hash is consistent but the absolute time has expired (e.g., the time interval corresponding to the most recent week has shifted), then only update the absolute time interval in the XML, keep the structured JSON structure unchanged, and re-enter S4 for compilation and execution.
[0050] This is the most common scenario: the hash is consistent, but the previously saved absolute time range (e.g., 2025-01-08 to 2025-01-15) is outdated today (e.g., 2025-01-22). The user wants the "most recent week," that is, 2025-01-15 to 2025-01-22. The system finds the relative time expression "most recent week" in the XML, so it doesn't discard the entire XML. Instead, it recalculates the new absolute time range for the current date and only updates the time in the XML. range Fields, other parts (select) fields , where condition, Group By, chart type (etc.) It remains unchanged. Then, this updated structured intent JSON is directly entered into S4 for recompilation and execution, skipping S3 as well. This ensures that the time range is correct and avoids re-calling the large model, making it highly efficient.
[0051] Ultimately, regardless of which branch is taken, the system will execute the SQL generated by S4 (which may come from a cached recompilation or from a recompilation after regenerating intents), and after obtaining the result set, render the report according to the chart type and output it to the user.
[0052] Example 2: Dynamic Fleet Report Generation System Based on Natural Language Intent Parsing This embodiment provides a fleet report dynamic generation system based on natural language intent parsing. The system is deployed on a multi-tenant SaaS-based fleet management platform to implement the method described in Embodiment 1. The system includes five core modules, which are sequentially connected to form a closed-loop compilation pipeline from natural language to secure SQL statements.
[0053] (1) Metadata dictionary management module This module, configured on the server side, is responsible for storing and managing the metadata dictionary. The metadata dictionary must at least contain the field name, data type, and allowed set of aggregation operations for each field (the specific content is the same as defined in Example 1S1). This module is also responsible for calculating the version hash of the current dictionary. hash =MD5 (canonical string)), and provides dictionary lookup interfaces and version hash retrieval interfaces. Other modules (intent extraction module, AST compilation and security injection module, report rendering and persistence module) all obtain dictionary constraints and version information through this module.
[0054] (2) Terminal request parsing module This module, deployed on the client or front-end gateway, receives natural language report requests from users via voice or text input. It performs preprocessing: if the request is voice, it calls a speech recognition service to transcribe it into text, then performs spell correction, sentence standardization, and parses relative time expressions (such as "last week") into absolute time intervals. The preprocessed standard query text is then sent to the intent extraction module. This module essentially corresponds to step S2 in Example 1.
[0055] (3) Intent extraction module This module is configured on the server side, connecting to both the metadata dictionary management module and the terminal request parsing module. It receives standard query text, retrieves the current list of field constraints (including field names, types, allowed aggregations, semantic aliases, etc.) from the metadata dictionary management module, constructs a prompt word template, and calls the large language model API to generate a structured intent JSON. After generation, this module performs post-processing based on the semantic aliases in the dictionary, mapping colloquial field names to standard physical field names. If multiple matching candidates are found, a first-level closed-loop feedback signal is triggered, returning the candidate list to the user for correction and regeneration. The final output structured intent JSON is sent to the AST compilation and security injection module. This module corresponds to step S3 in Example 1.
[0056] (4) AST compilation and security injection module This module connects to both the intent extraction module and the metadata dictionary management module. It receives structured intent JSON, retrieves the dictionary definition from the metadata dictionary management module, and performs compilation validation (field existence, aggregation validity, operator type matching, Group By consistency, enumeration value validity, etc.). After successful validation, it generates an intermediate AST and, when converting the AST to SQL statements, forcibly appends the current user's tenant isolation condition within the code generation function. id =Current tenant), output secure SQL statement. If compilation verification fails, this module triggers the first-level closed-loop feedback signal, sending the error information and candidate correction options back to the intent extraction module, requesting the regeneration of the structured intent JSON. This module corresponds to step S4 in Example 1.
[0057] (5) Report rendering and persistence module This module connects to the AST compilation and security injection modules, responsible for executing secure SQL statements to obtain result sets, and dynamically rendering reports based on the chart types (such as bar, line, pie, etc.) in the structured intent JSON, outputting them to the user. When the user saves the report, this module serializes the structured intent JSON into an XML configuration file, appends the version hash of the current metadata dictionary and a relative time expression (not absolute time), and stores it in the cache. When the user triggers the same report again, this module first verifies whether the version hash in the XML matches the version hash of the current metadata dictionary. If the hash is consistent and the absolute time interval has not expired, the structured intent JSON in the XML is directly sent to the AST compilation and security injection module (skipping the intent extraction module, i.e. skipping the S3 large language model call). If the hashes do not match, the XML configuration is discarded, triggering a second-level closed-loop feedback signal that sends the original query intent back to the intent extraction module, requiring the regeneration of the structured intent JSON. If the hash is consistent but the absolute time has expired, only the absolute time range in the XML is updated, other intent structures are preserved, and the XML is re-entered into the AST compilation and security injection module.
[0058] This module corresponds to step S5 in Example 1.
[0059] The present invention has been described in the above-described embodiments; however, these embodiments are merely examples for implementing the present invention. It must be noted that the disclosed embodiments do not limit the scope of the present invention. Conversely, any modifications and refinements made without departing from the spirit and scope of the present invention are within the scope of patent protection of the present invention.
Claims
1. A method for dynamically generating fleet reports based on natural language intent parsing, characterized in that, Includes the following steps: S1: Configure and store a metadata dictionary, which consists of multiple field entries, each containing a physical field name (field). name Data type type List of allowed aggregate functions aggregations Three core attributes; S2: Using the metadata dictionary as the constraint domain, receive the user's natural language report request and preprocess it into standard query text, including parsing relative time into absolute time interval; S3: Using the standard query text as input, generate a structured intent JSON through the large language model, subject to the field set and allowed operation constraints defined by the metadata dictionary. The structured intent JSON includes the fields to be displayed, filtering conditions, grouping dimensions, chart type, and time range. S4: Using the structured intent JSON as input, perform compilation verification through the AST compiler. After the compilation verification is successful, an intermediate AST is generated. When the intermediate AST is converted into a secure SQL statement, the tenant isolation condition of the current user is forcibly attached inside the code generation function of the AST compiler. The compilation verification includes: checking whether each field exists in the metadata dictionary, checking whether the aggregation operation belongs to the allowed set of the field, checking the matching of the operator and the data type, and checking whether the non-aggregate Select field appears in Group By; S5: Execute the secure SQL statement to obtain the result set, dynamically render the report according to the chart type information in the structured intent JSON, and output the final report.
2. The method as described in claim 1, characterized in that, It also includes the first-level closed-loop feedback: when the S4 detects that a field does not exist, the aggregation is illegal, the type does not match, or the semantic ambiguity during the compilation and verification process, it triggers the intent clarification rollback process, returns a list of candidate fields or error messages to the user, receives the user's selection or correction, and feeds back to S3 to regenerate the structured intent JSON and perform a new round of compilation and verification.
3. The method as described in claim 1, characterized in that, It also includes a second-level closed-loop feedback: when the final report is saved in S5, the structured intent JSON is serialized into an XML configuration file and the version hash of the current metadata dictionary is attached; when the report is triggered again, if the version hash in the XML is inconsistent with the version hash of the current metadata dictionary, the XML configuration is discarded and fed back to S3 to regenerate the structured intent JSON and recompile and execute it.
4. The method as described in claim 1, characterized in that, The metadata dictionary also contains a list of semantic aliases for each field; after the large language model in S3 outputs the structured intent JSON, the colloquial field names in the structured intent JSON are mapped to standard field names according to the list of semantic aliases; when there are multiple matching candidates for the semantic alias mapping, the intent clarification fallback process in the first-level closed-loop feedback is triggered: the candidate field list is returned to the user, the structured intent JSON is corrected after receiving the user's selection, and the process is re-entered into S4 for compilation and verification.
5. The method as described in claim 1, characterized in that, The injection logic that forces the addition of tenant isolation conditions in S4 is located inside the AST to SQL code generation function and is not affected by the structured intent JSON content generated by S3; even if the Where condition in the structured intent JSON is empty, the AST compiler's code generation function still unconditionally adds the tenant isolation conditions.
6. The method as described in claim 1, characterized in that, When the structured intent JSON is serialized into an XML configuration file in S5, in addition to the version hash of the metadata dictionary, a relative time expression is also retained in the form of a logical expression. When the second-level closed-loop feedback is triggered, if the version hash is consistent but the absolute time has expired, only the absolute time range in the XML is updated, and the complete recompilation process is not triggered.
7. The method as described in claim 1, characterized in that, In the metadata dictionary, fields of enumeration type are further checked during S4 compilation and verification to see if the value in the Where condition is in the list of valid values for the enumeration field. If not, a compilation error is reported and the query is blocked, triggering the first level of closed-loop feedback.
8. The method as described in claim 1, characterized in that, In the S4 compilation verification, if a non-aggregate Select field does not appear in Group By, a compilation error will occur and the query will be blocked, triggering the first-level closed-loop feedback.
9. The method as described in claim 1, characterized in that, The method for dynamically generating fleet reports based on natural language intent parsing is deployed in a multi-tenant SaaS architecture, where each tenant has an independent metadata dictionary view; the tenant isolation condition that is forcibly attached in S4 ensures that the query results only contain data from the current tenant.
10. A system for dynamically generating fleet reports based on natural language intent parsing, characterized in that, include: The metadata dictionary management module, configured on the server, is used to store the metadata dictionary. The metadata dictionary contains at least the field name, data type, and allowed set of aggregation operations for each field, and calculates the version hash of the current dictionary. The terminal request parsing module is used to receive users' natural language report requests and preprocess them into standard query text, including parsing relative time expressions into absolute time intervals. The intent extraction module, configured on the server and connected to the metadata dictionary management module, is used to call the large language model and, with the metadata dictionary as the constraint domain, convert the standard query text into structured intent JSON. The AST compilation and security injection module is connected to the intent extraction module and the metadata dictionary management module, respectively. It is used to perform compilation and verification on the structured intent JSON. After the verification is successful, an intermediate AST is generated. When converting the intermediate AST into an SQL statement, the current user's tenant isolation condition is forcibly attached inside the code generation function, and a secure SQL statement is output. The report rendering and persistence module is connected to the AST compilation and security injection module. It is used to execute the secure SQL statement to obtain the result set, dynamically render the report according to the chart type in the structured intent JSON, and serialize the structured intent JSON into an XML configuration file and attach the version hash when saving the report. Specifically, when the AST compilation and security injection module fails to compile and verify, it triggers a first-level closed-loop feedback signal, which is fed back to the intent extraction module to regenerate the structured intent JSON. When the report rendering and persistence module triggers the report again, if the version hash in the XML configuration file is inconsistent with the version hash of the current metadata dictionary, it triggers a second-level closed-loop feedback signal, which is fed back to the intent extraction module to regenerate the structured intent JSON.
Citation Information
Patent Citations
Intelligent report generation method, system and equipment based on NL2SQL (Non-Layer 2Structured Query Language) and medium
CN120596499A