A knowledge graph-based method and system for automatic programming generation

By using a recursive semantic fusion and feedback correction mechanism, the semantic understanding and constraint activation are dynamically optimized, solving the problem of code generation deviating from user intent in existing technologies, and achieving high-quality code generation that conforms to multi-level constraints.

CN121597180BActive Publication Date: 2026-04-03WUXI SHENGDING INTELLIGENT TECH CO LTD
View PDF 2 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2026-01-28
Publication Date
2026-04-03

AI Technical Summary

Technical Problem

Existing knowledge graph-based code generation methods rely on the accuracy of early parsing and alignment, making it difficult to dynamically optimize semantic understanding and contextual constraints. This results in generated code semantics deviating from user intent, and the constraints are rigid, making it difficult to guarantee the correctness of the code's syntax, business logic, and system architecture.

Method used

A recursive semantic fusion mechanism and a feedback correction mechanism are adopted. By constructing an initial semantic perception network and a multi-level constraint activation process, entity boundaries and attributes are dynamically corrected to generate intermediate semantic alignment maps. Then, a constraint-driven semantic synthesis engine and a feedback optimizer are used to achieve iterative optimization of the code.

Benefits of technology

It improves the robustness and adaptability of code generation, ensures that the generated code conforms to multi-dimensional design specifications, enhances code quality and intent consistency, and avoids interference from irrelevant constraints.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121597180B_ABST
    Figure CN121597180B_ABST
Patent Text Reader

Abstract

This invention relates to the field of knowledge graph driver generation technology, specifically a method and system for automatic programming generation based on knowledge graphs. The method includes: iteratively aligning and dynamically correcting user intent entities with the knowledge graph through a recursive semantic fusion mechanism; triggering multi-level constraint activation based on the alignment results to accurately obtain relevant syntactic, logical, and architectural constraints; utilizing a constraint-driven semantic synthesis engine to reorganize entities into candidate code abstract semantic graphs and instantiating them into code snippets; validating the generation results through a sandbox and feeding back semantic mismatch information to the front-end fusion process, forming a self-optimizing closed loop. This method achieves dynamic iterative optimization of semantic understanding and contextualized intelligent application of programming constraints, effectively improving the accuracy and reliability of generated code.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of knowledge graph driver generation technology, and in particular to a method and system for automatic generation of knowledge graph-based programming. Background Technology

[0002] Currently, knowledge graph-based automatic code generation methods typically employ a sequential processing flow. A common approach is to map natural language descriptions to fixed concept nodes in the knowledge graph through semantic parsing, and then directly generate code based on predefined code templates or rule sets. Another approach is to construct a structured graph containing rich programming knowledge and invoke relevant rules either once or statically during the generation process. These methods rely on the accuracy of the initial parsing and alignment, and impose the constraints of the knowledge graph globally or pre-bound in the generation process.

[0003] Existing technical solutions have shortcomings. Semantic parsing and knowledge alignment are often one-off processes. When the initial parsing is ambiguous or the match with the knowledge graph is inaccurate, the semantics of the generated code will deviate from the user's true intent, and the system itself cannot correct this fundamental comprehension bias. Furthermore, the application of programming constraints from the knowledge graph is rather rigid, either involving simple retrieval of association rules or loading all potentially relevant constraints, lacking dynamic awareness of the specific alignment context. This results in the constraints' guiding role being either incomplete or conflicting, making it difficult to simultaneously guarantee the correctness of the code at the syntactic, business logic, and system architecture levels.

[0004] There is a need for a code generation method that can dynamically optimize semantic understanding and intelligently activate contextual constraints. The key is to enable the system to use subsequent execution feedback to iteratively correct the semantic alignment results of the front end, and to allow the constraints in the knowledge graph to be accurately and hierarchically activated and applied according to the real-time alignment status, thereby improving the intent consistency and overall quality of the generated code. Summary of the Invention

[0005] The purpose of this invention is to address the shortcomings of existing technologies by proposing a knowledge graph-based automatic programming generation method and system.

[0006] To achieve the above objectives, the present invention adopts the following technical solution: a method for automatic programming generation based on knowledge graphs, comprising:

[0007] Construct an initial semantic awareness network and extract the core functional intent entities and data operation entities from it;

[0008] A recursive semantic fusion mechanism is adopted to iteratively align and fuse the functional intent entities and data operation entities with a pre-built knowledge graph containing programming concepts and domain rules. In each iteration, the boundaries and attributes of the entities are corrected and an intermediate semantic alignment mapping is generated.

[0009] Based on the intermediate semantic alignment mapping, a multi-level constraint activation process is triggered, which activates the syntactic constraints, logical constraints, and architectural constraints related to the aligned entities from the knowledge graph.

[0010] Through a constraint-driven semantic synthesis engine, the syntactic constraints, logical constraints, and architectural constraints activated by the multi-level constraint activation process are used as guiding rules to reorganize and connect entities in the intermediate semantic alignment mapping, generating a candidate code abstract semantic graph.

[0011] A feedback-based semantic graph optimizer is deployed to instantiate the candidate code abstract semantic graph into preliminary code fragments. The preliminary code fragments are then verified through a preset lightweight execution sandbox. Semantic mismatch information generated during the verification process is fed back to the recursive semantic fusion mechanism to initiate a new round of iterative alignment.

[0012] Preferably, the construction of the initial semantic awareness network specifically includes:

[0013] The initial semantic awareness network is used to receive and understand unstructured natural language text input by the user that describes programming requirements.

[0014] Configure a hierarchical text scanner to parse unstructured natural language text input by the user layer by layer, and identify and tag verb phrases, noun phrases and keywords indicating conditions or loops;

[0015] The layered text scanner identifies verb phrases as potential operation instructions, maps noun phrases as potential data objects or parameters, and establishes a preliminary dependency relationship between verb phrases and noun phrases.

[0016] By using a domain dictionary to perform semantic disambiguation on the mapped potential operation instructions and potential data objects, each entity is assigned a precise meaning in the programming context, forming a structured set of functional intent entities and data operation entities.

[0017] Preferably, the recursive semantic fusion mechanism specifically includes:

[0018] Each entity in the structured set of functional intent entities and data operation entities is used as a query item for preliminary matching in the knowledge graph to obtain a set of candidate nodes for each entity in the knowledge graph.

[0019] Analyze the graph relationships between the candidate node sets, and modify and enhance the entity relationships in the structured functional intent entity and data operation entity sets based on the graph relationships;

[0020] Based on the corrected entity relationships, the semantic fit between entities and knowledge graph nodes is calculated, the optimal node matching pair is selected, and an intermediate semantic alignment mapping for one iteration is formed.

[0021] Determine whether there are semantically ambiguous or conflicting entities in the current intermediate semantic alignment mapping. If so, resubmit the relevant entities and their context to the initial semantic perception network for re-analysis and initiate the next recursive semantic fusion.

[0022] Preferably, the step of triggering a multi-level constraint activation process based on the intermediate semantic alignment mapping specifically includes:

[0023] The intermediate semantic alignment mapping is analyzed to identify the core entities that have been successfully aligned to the knowledge graph nodes;

[0024] Starting with the core entity, traverse the relation edges in the knowledge graph, collect all directly related constraint nodes marked as grammatical rules, and form a set of grammatical constraints;

[0025] In the knowledge graph, find nodes that have an indirect logical implication relationship with the core entity, and transform the logical premises or results represented by the nodes into logical constraints to form a set of logical constraints.

[0026] From the architecture-level subgraph of the knowledge graph, extract the interface definitions and data flow specifications related to the module or component to which the current core entity belongs, and form a set of architecture constraints.

[0027] Preferably, the constraint-driven semantic synthesis engine uses the syntactic constraints, logical constraints, and architectural constraints activated by the multi-level constraint activation process as guiding rules to reorganize and connect entities in the intermediate semantic alignment map, generating a candidate code abstract semantic graph, specifically including:

[0028] Based on the set of grammatical constraints, an expression template and combination order conforming to the grammar of the target programming language are determined for the entities in the intermediate semantic alignment map;

[0029] Apply the set of logical constraints to insert necessary condition judgment nodes and loop control nodes into the expression template, and determine the effective scope and logical connection relationship of the condition judgment nodes and loop control nodes;

[0030] Following the set of architectural constraints, the synthesized code logic units are organized into modules or functions that conform to the architectural specifications, and the calling relationships and parameter passing interfaces between modules or functions are defined.

[0031] The entities, control nodes, and modules, after being organized by syntactic, logical, and architectural constraints, are encapsulated in the form of a graph structure to generate the candidate code abstract semantic graph with a clear structure and executability.

[0032] Preferably, the deployment of the feedback-based semantic graph optimizer specifically includes:

[0033] Configure a graph-to-code converter to translate the nodes and edges in the candidate code abstract semantic graph into specific code statements in the target programming language according to predefined conversion rules, thereby instantiating them into preliminary code fragments;

[0034] The initial code snippet is loaded into a lightweight execution sandbox, which contains a restricted runtime environment and a monitor for detecting runtime exceptions.

[0035] Run the initial code snippet, capture runtime exceptions, type errors or logical contradictions through the monitor, and convert the error information into a semantic mismatch description of a specific node or edge in the abstract semantic graph of the candidate code;

[0036] The semantic mismatch description is encapsulated into a feedback data packet and sent back to the entity relationship correction stage of the recursive semantic fusion mechanism, instructing it to re-evaluate and adjust the alignment or relationship of the relevant entities.

[0037] Preferably, the step of using a domain dictionary to perform semantic disambiguation on the mapped potential operation instructions and potential data objects, assigning each entity a precise meaning in the programming context, and forming a structured set of functional intent entities and data operation entities includes:

[0038] Query the domain dictionary to obtain all possible interpretations of each potential operation instruction in all programming contexts;

[0039] Query the domain dictionary to obtain all data types and structure definitions corresponding to each potential data object;

[0040] Based on the preliminary dependency relationship between verb phrases and noun phrases, the programming operation semantics that best match the current context are selected from the possible interpretations;

[0041] Select data types from the data types and structure definitions that match the semantic requirements of the current programming operation;

[0042] The selected programming operation semantics are assigned corresponding potential operation instructions to form functional intent entities;

[0043] The selected data types are assigned to the corresponding potential data objects to form data operation entities;

[0044] The functional intent entity and the data operation entity are linked according to the preliminary dependency relationship to form a structured set of functional intent entities and data operation entities.

[0045] Preferably, the step of parsing the intermediate semantic alignment mapping to identify the core entities that have been successfully aligned to the knowledge graph nodes includes:

[0046] Iterate through all the matching pairs between entities and knowledge graph nodes recorded in the intermediate semantic alignment mapping;

[0047] Check whether the semantic fit of each matching pair exceeds the preset confidence threshold;

[0048] The entities corresponding to matching pairs whose semantic fit exceeds the confidence threshold are marked as successfully aligned entities;

[0049] Filter out the entities with the highest dependency weight in the initial semantic awareness network from the successfully aligned entities;

[0050] The selected entities are identified as core entities, and the target node identifier corresponding to each core entity in the knowledge graph is recorded.

[0051] Preferably, the step of following the set of architectural constraints, organizing the synthesized code logic units into modules or functions that conform to the architectural specifications, and defining the calling relationships and parameter passing interfaces between modules or functions, includes:

[0052] Read the module partitioning rules and function encapsulation principles defined in the architecture constraint set;

[0053] According to the module division rules, code logic units that share a common data source or execute coherent business logic are aggregated into the same module boundary;

[0054] According to the aforementioned function encapsulation principle, code logic units that complete specific subtasks are encapsulated into independent function units;

[0055] Based on the interface specifications defined in the set of architectural constraints, generate an external function call entry point for each module;

[0056] Analyze the data flow between function units within the analysis module, and define the parameter types, parameter order, and return value types required when calling functions based on the parameter passing specifications in the architecture constraint set.

[0057] Define cross-module function call chains and parameter interfaces that are passed along with the call chains based on business logic dependencies between modules.

[0058] Preferably, the present invention also includes a knowledge graph-based automatic programming generation system, the system including a memory, a processor, and a computer program stored in the memory and running on the processor, wherein when the processor executes the computer program, it implements the steps of the knowledge graph-based automatic programming generation method described above.

[0059] Compared with the prior art, the advantages and positive effects of the present invention are as follows:

[0060] A recursive semantic fusion and feedback correction mechanism is employed, incorporating semantic mismatches discovered during code instantiation and sandbox validation as structured feedback back into the front-end entity alignment process. This design breaks the unidirectional nature of traditional processes, establishing a closed loop that corrects semantic understanding from the execution results. The system no longer relies entirely on the accuracy of the initial parsing but possesses the ability to self-adjust based on actual operational performance. Entity boundaries and attributes are dynamically corrected during iteration, enabling the parsing of ambiguous or complex user intents to gradually become more precise with each generation attempt, enhancing the method's adaptability to unconventional or ambiguous requirements and the robustness of the generated results.

[0061] Deploying a dynamically triggered, multi-level constraint activation network transforms the constraint application model from static preloading to dynamic, on-demand activation. The intermediate semantic alignment mapping acts as a trigger; once an entity successfully aligns with a knowledge graph concept, its associated syntactic, logical, and architectural constraints are automatically inferred from the graph and activated hierarchically. The activation scope and depth of constraints are closely dependent on the currently established entity alignment state, ensuring high contextual relevance of the guiding rules. This mechanism avoids interference from irrelevant constraints while guaranteeing the timely intervention of necessary constraints, enabling the final synthesized code abstract semantic graph to inherently and consistently meet multi-dimensional, multi-level design specifications and best practice requirements. Attached Figure Description

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

[0063] Figure 1 This is a flowchart of the knowledge graph-based automatic programming generation method described in this invention.

[0064] Figure 2A flowchart for constructing the initial semantic awareness network.

[0065] Figure 3 This is a comparison chart of the semantic fit between entities and knowledge graph nodes.

[0066] Figure 4 Activate the matching quality heatmap for multi-level constraints.

[0067] Figure 5 A flowchart illustrating how a constraint-driven semantic synthesis engine works. Detailed Implementation

[0068] The technical solution of the present invention will now be described with reference to the accompanying drawings.

[0069] In embodiments of the present invention, words such as "exemplarily," "for example," etc., are used to indicate that something is an example, illustration, or description. Any embodiment or design described as "exemplary" in the present invention should not be construed as being more preferred or advantageous than other embodiments or designs. Specifically, the use of the word "exemplary" is intended to present the concept in a concrete manner. Furthermore, in embodiments of the present invention, the meaning expressed by "and / or" can be both, or either one.

[0070] In the embodiments of this invention, the terms "image" and "picture" may sometimes be used interchangeably. It should be noted that, without emphasizing the distinction between them, they convey the same meaning. Similarly, the terms "of," "corresponding (relevant)," and "corresponding" may sometimes be used interchangeably. It should be noted that, without emphasizing the distinction between them, they convey the same meaning.

[0071] In this embodiment of the invention, sometimes a subscript such as W1 may be written in a non-subscript form such as W1. When the difference is not emphasized, the meaning they express is the same.

[0072] To make the technical problems, technical solutions and advantages of the present invention clearer, a detailed description will be given below in conjunction with the accompanying drawings and specific embodiments.

[0073] See Figure 1An initial semantic awareness network is constructed to receive and parse users' unstructured natural language requests, extracting core functional intent entities and data operation entities. A recursive semantic fusion mechanism is employed to iteratively align and fuse these extracted entities with a pre-built knowledge graph containing rich programming concepts and domain rules. In each iteration, the entity boundaries and attributes are corrected, generating an intermediate semantic alignment map. Based on this intermediate semantic alignment map, the system triggers a multi-level constraint activation process, which automatically activates syntactic, logical, and architectural constraints associated with the aligned entities from the knowledge graph. A constraint-driven semantic synthesis engine is then activated, using the aforementioned activated multi-level constraints as guiding rules to reorganize and connect the entities in the intermediate semantic alignment map, thereby generating a structured candidate code abstract semantic graph. Deploy a feedback-based semantic graph optimizer; this optimizer instantiates candidate code abstract semantic graphs into preliminary code snippets and puts them into a pre-defined lightweight execution sandbox for verification; any semantic mismatch information generated during the sandbox verification process will be encapsulated as feedback and sent back to the recursive semantic fusion mechanism, thereby initiating a new round of iterative alignment and optimization until code that meets the requirements is generated.

[0074] In one embodiment of the present invention, see [reference] Figure 2 The initial construction of the semantic awareness network begins with receiving unstructured natural language text input from the user. In an example scenario, the user inputs the natural language text "read the file and calculate the average value," and the construction process begins. A hierarchical text scanner first parses the text layer by layer. In the first layer, it identifies the verb phrases "read" and "calculate," as well as the noun phrases "file" and "average value," and marks the keyword "and" indicating a connection. At deeper levels of parsing, the hierarchical text scanner further analyzes the internal structure of the phrases, establishing a verb-object relationship between "read" and "file," and between "calculate" and "average value." In practice, the mapping process maps the identified verb phrases to potential operation instructions and the noun phrases to potential data objects. The verb phrase "read" is mapped to one potential operation instruction, labeled "read operation"; the verb phrase "calculate" is mapped to another potential operation instruction, labeled "calculate operation." The noun phrase "file" is mapped to a potential data object, labeled "file object"; the noun phrase "average" is mapped to another potential data object, labeled "average object". Preliminary dependencies are established, where "read operation" depends on "file object" and "calculation operation" depends on "average object".

[0075] In some embodiments, semantic fit calculation is used to filter from possible interpretations. Based on the initial dependency relationship between the verb phrase and the noun phrase, the context of the potential operation instruction "read operation" is the operation object "file object". From the possible interpretations of "read operation", the programming operation semantics most relevant to "file object" are filtered out. The semantic fit of each possible interpretation with the current context is calculated using the following formula:

[0076]

[0077] in: The semantic fit score represents the i-th possible interpretation. This represents the number of feature matches between this definition and the definition of "file object" in the domain dictionary. The total number of benchmark items representing all relevant features. The semantic fit score for the interpretation "open a file from disk and retrieve its contents" was calculated, and therefore it was selected. Similarly, to match the selected "file read" semantic, the data type "data buffer type representing the byte stream of file content" was selected from the data type definition of "file object". For "calculation operation", based on its dependency on "average object", "arithmetic average of a set of values" was selected as the programming operation semantic, and "floating-point type" was selected as the data type for "average object".

[0078] Understandably, the composition of the domain dictionary directly impacts disambiguation accuracy. The content of the domain dictionary needs to be pre-extracted and constructed from the official documentation of the target programming language, application programming interface (API) documentation of commonly used libraries, and domain terminology manuals. Dictionary entries are organized in a machine-readable, structured format, explicitly listing the precise meaning of each term in different programming contexts, its associated data structures, and usage constraints. The structured sets of functional intent entities and data manipulation entities are encapsulated and transmitted in an internally defined graph format. Nodes in the graph represent entities, edges represent dependencies between entities, and each node is accompanied by precise semantic labels and type attributes obtained from the domain dictionary.

[0079] In one embodiment of the present invention, the recursive semantic fusion mechanism receives a structured set of functional intent entities and data operation entities from an initial semantic awareness network. The set includes functional intent entities "file reading intent" and "calculate average intent," as well as data operation entities "file data entity" and "average entity." In a specific implementation, each entity in the structured set of functional intent entities and data operation entities is treated as an independent query item and initially matched against a pre-constructed knowledge graph. The matching process retrieves a set of candidate nodes from the knowledge graph for each entity.

[0080] In practical implementation, the graph relationships between candidate node sets are analyzed, and the entity relationships in the structured functional intent entities and data operation entities are modified and enhanced based on these relationships. In the knowledge graph, there is a "return" relationship edge between the "open() function node" and the "file object node," and an "operate on" relationship edge between the "read() method node" and the "byte stream node." By analyzing these relationships, the dependency relationship between the functional intent entity "file read intent" and the data operation entity "file data entity" is modified, enhancing its relationship type to "open and read." Simultaneously, based on the "input" relationship between the "numerical list" node and the "sum() function node" in the knowledge graph, the relationship between "calculate average intent" and the "average entity" is modified, enhancing it to "summation and division."

[0081] In some embodiments, based on the modified entity relationships, the semantic fit between entities and knowledge graph nodes is calculated. The semantic fit quantifies the degree of matching between entities and nodes. The formula for calculating the semantic fit is:

[0082]

[0083] in: Represents the semantic fit score. The set of attributes representing an entity. The set of attributes representing nodes in a knowledge graph. A set of contextual relationships representing entity associations. Represents the set of contextual relationships associated with nodes in a knowledge graph. It is the weight coefficient for relation matching.

[0084] In some embodiments, the optimal node matching pairs are selected based on semantic fit scores to form an iterative intermediate semantic alignment mapping. The functional intent entity "file reading intent" and the knowledge graph node "open() function node" are identified as the optimal matching pair; the data operation entity "file data entity" and the knowledge graph node "file object node" are identified as the optimal matching pair; the functional intent entity "calculate average intent" and the combination of the knowledge graph nodes "sum() function node" and "division operation node" are identified as the optimal matching pair; and the data operation entity "average entity" and the knowledge graph node "floating-point number node" are identified as the optimal matching pair. These matching pairs are recorded in the intermediate semantic alignment mapping, and the mapping structure records the entity identifier, node identifier, and corresponding semantic fit score.

[0085] Optionally, it determines whether there are semantically ambiguous or conflicting entities in the current intermediate semantic alignment mapping, checks whether the semantic fit scores of all matching pairs in the mapping are higher than a preset threshold, and whether the entity relationships are consistent with the relationship logic in the knowledge graph. If there are semantically ambiguous or conflicting entities in the intermediate semantic alignment mapping, the relevant entities and their contexts are resubmitted to the initial semantic perception network for re-analysis. The ambiguous entity "file data entity" and its associated "file reading intent" context are re-inputted into the initial semantic perception network to start the next recursive semantic fusion process. The initial semantic perception network combines the new context information to perform semantic disambiguation again, generating an updated set of structured functional intent entities and data operation entities. The recursive semantic fusion mechanism re-executes the matching, relationship correction, and filtering steps based on the updated set.

[0086] It is understandable that the quality of knowledge graph construction directly affects the effectiveness of recursive semantic fusion. A knowledge graph needs to contain complete programming language syntax nodes, commonly used library function nodes, data structure nodes, and rich semantic relationships and constraints between nodes. It is also understandable that the iteration termination condition of the recursive semantic fusion mechanism can be set as follows: the semantic fit score of all entities in the intermediate semantic alignment map exceeds a high threshold and there are no logical conflicts; or the number of iterations reaches a preset upper limit. When either condition is met, the recursive process stops and the final intermediate semantic alignment map is output.

[0087] See Figure 3 This is a comparison chart of the semantic fit between entities and knowledge graph nodes, demonstrating the matching quality of four sets of functional / data entities and knowledge graph nodes during the "recursive semantic fusion stage." All matching pairs passed the confidence threshold of 0.8, validating the effectiveness of the recursive semantic fusion mechanism and providing a reliable semantic foundation for subsequent code generation. A high fit score indicates that the system can accurately identify functional and data entities in natural language requirements and map them to corresponding nodes in the knowledge graph, a crucial prerequisite for automatically generating high-quality code. With all matching pairs meeting the required fit criteria, satisfying the iteration termination condition for recursive semantic fusion, the system can directly proceed to the subsequent constraint activation and code generation stages.

[0088] In one embodiment of the present invention, the multi-level constraint activation process is triggered by parsing the intermediate semantic alignment map, which originates from the output of the recursive semantic fusion mechanism. Parsing the intermediate semantic alignment map identifies core entities successfully aligned to knowledge graph nodes; this identification process follows specific steps. All entity-knowledge graph node matching pairs recorded in the intermediate semantic alignment map are traversed. These matching pairs include functional intent entities such as "file reading intent" and knowledge graph nodes such as "open() function node," and data operation entities such as "file data entity" and knowledge graph nodes such as "file object node." The semantic fit of each matching pair is checked to see if it exceeds a preset confidence threshold, which is set to 0.85. Entities corresponding to matching pairs with semantic fit exceeding the confidence threshold are marked as successfully aligned entities; for example, "file reading intent" and "file data entity" are marked. From the successfully aligned entities, entities with the highest dependency weights in the initial semantic awareness network are selected. These dependency weights reflect the centrality of the entity in the original query. The selected entities are identified as core entities, and the target node identifier corresponding to each core entity in the knowledge graph is recorded.

[0089] In some embodiments, starting from the core entity, the relation edges in the knowledge graph are traversed to collect all directly related constraint nodes marked as grammatical rules. Starting from the core entity "open() function node", the relation edges in the knowledge graph are traversed to collect the grammatical rule constraint nodes "function call must contain parentheses" and "first parameter is a file path string". Starting from the core entity "sum() function node", the grammatical rule constraint nodes "function parameter must be an iterable object" are collected. Starting from the core entity "division operation node", the grammatical rule constraint nodes "operator is ' / '" and "two operands are required" are collected. These grammatical rule constraint nodes together form a set of grammatical constraints.

[0090] In some embodiments, nodes with indirect logical implications to core entities are searched within the knowledge graph. The core entity "open() function node" is connected to the "FileNotFoundError exception node" in the knowledge graph through a "may trigger" relationship. The "FileNotFoundError exception node" logically implies "the existence of the file needs to be checked," and this logical premise is transformed into a logical constraint. The core entity "division operation node" is connected to the "divisor non-zero node" through a "requirement" relationship. The "divisor non-zero node" logically implies "the denominator cannot be zero," and this logical result is transformed into another logical constraint. The search process involves traversing multi-hop relationship paths in the knowledge graph, discovering these indirect logical connections, and transforming the logical premises or results represented by the connected nodes into logical constraints, forming a set of logical constraints.

[0091] Optionally, the search range of the multi-level constraint activation process within the knowledge graph is controlled by the activation radius parameter R. The constraint collection process is not an unlimited traversal, but rather limited to a subgraph centered on the core entity node and with the activation radius R as the number of hops. The value of the activation radius R can be configured according to the complexity of the specific programming task. For simple script generation, R can be set to 2; for complex tasks involving multiple modules, R can be set to 3 or greater. The formula for estimating the size of the constraint collection is:

[0092]

[0093] in: This represents the estimated total number of constraint nodes collected. Represents the number of core entities, This represents the out-degree of the i-th core entity node in the knowledge graph. The weight coefficient represents the i-th core entity.

[0094] It is understandable that the multi-level constraint activation process is a static graph query process, whose execution does not depend on the actual running of the code, but is entirely based on the pre-encoded programming knowledge, logical rules, and design specifications in the knowledge graph. It is also understandable that the sets of syntactic constraints, logical constraints, and architectural constraints are organized in a machine-readable standardized format after formation, such as using assertion languages ​​or structured rule objects, so that subsequent constraint-driven semantic synthesis engines can directly read and use them.

[0095] See Figure 4 This is a heatmap of multi-level constraint activation matching quality, showing the semantic matching degree between different types of constraint nodes and the three types of constraints: syntax, logic, and architecture, during the "multi-level constraint activation phase." The heatmap visually presents the matching quality of different constraint nodes, helping to identify which constraints are clearly defined and which need optimization, providing data support for the iterative improvement of the knowledge graph. High-fit constraints (such as module architecture and exception handling) provide clear rule guidance for code generation, ensuring the generated code is grammatically, logically, and architecturally sound. Low-fit constraints (such as parameter requirements) are the focus of subsequent recursive semantic fusion and knowledge graph updates; optimizing these constraints can improve the overall accuracy of code generation.

[0096] In one embodiment of the present invention, see [reference] Figure 5The constraint-driven semantic synthesis engine receives sets of syntactic constraints, logical constraints, and architectural constraints from a multi-level constraint activation process, as well as intermediate semantic alignment maps from a recursive semantic fusion mechanism. Based on the syntactic constraint set, it determines the expression templates and combination order of entities in the intermediate semantic alignment maps that conform to the target programming language syntax. The intermediate semantic alignment maps contain the matching relationships between entities and knowledge graph nodes. The constraints "function calls must contain parentheses" and "the first parameter is a file path string" are obtained from the syntactic constraint set. These constraints are applied to the functional intent entity "file reading intent" that matches the "open() function node," determining its expression template to be "open(file_path)." The constraints "function parameters must be iterable objects," "the operator is ' / '," and "two operands are required" are obtained from the syntactic constraint set. These constraints are applied to the functional intent entities "calculate average intent" that match the "sum() function node" and the "division operation node," determining its expression template to be "sum(iterable) / len(iterable)." The order of combination between entities is determined by data flow dependencies. The output of the "File Read Intent" is the input of the "Calculate Average Intent," therefore the combination order is "File Read Intent" first, followed by "Calculate Average Intent." See Table 1.

[0097] Table 1: Intermediate Semantic Alignment Map

[0098]

[0099] In some embodiments, a set of logical constraints is applied to insert necessary conditional decision nodes and loop control nodes into the expression template. The logical constraint "file existence needs to be checked" is obtained from the set of logical constraints; this constraint originates from the logical implication of the "FileNotFoundError exception node". Based on this logical constraint, a conditional decision node is inserted before the expression template "open(file_path)". The conditional expression of this node is "file path exists". The true branch of the node executes "open(file_path)", and the false branch throws a "file not found exception". The logical constraint "denominator cannot be zero" is obtained from the set of logical constraints; this constraint originates from the logical implication of the "divisor non-zero node". Based on this logical constraint, another conditional decision node is inserted around the expression template "sum(iterable) / len(iterable)". The conditional expression of this node is "len(iterable)>0". The true branch of this node performs a division operation, and the false branch returns 0 or throws an exception. The scope of application and logical connection of the condition judgment node are determined based on the business logic. The file existence check includes the file opening operation, and the non-zero division check includes the division operation. The two are executed sequentially.

[0100] In some embodiments, the synthesized code logic units are organized into module or function boundaries that conform to the architectural specifications, following the set of architectural constraints. The module partitioning rules defined in the set of architectural constraints, namely "functional modularity" and the function encapsulation principles "should be encapsulated as independent functions" and "functions should have explicit input parameters and return values," are read. According to the "functional modularity" module partitioning rule, code logic units that share a common data source or execute coherent business logic are aggregated into the same module boundary. For example, the file reading and average calculation logic units operate on the same data and are therefore aggregated into a module boundary named "DataProcessor." According to the "should be encapsulated as independent functions" function encapsulation principle, code logic units that complete specific subtasks are encapsulated as independent function units. The file reading logic is encapsulated as the "read_file_data" function unit, and the average calculation logic is encapsulated as the "calculate_average" function unit. Based on the interface specification defined in the set of architectural constraints, "functions should have explicit input parameters and return values," an external function call entry point is generated for the "DataProcessor" module.

[0101] Optionally, analyze the data flow between function units within the module to define the interface. Analyze the data flow between the "read_file_data" function unit and the "calculate_average" function unit. The output of the "read_file_data" function unit is the file content data, which serves as the input to the "calculate_average" function unit. According to the parameter passing specifications in the architectural constraint set, define the parameter type required for the "read_file_data" function call as string type, the parameter order as the first parameter, and the return value type as list type; define the parameter type required for the "calculate_average" function call as list type, the parameter order as the first parameter, and the return value type as floating-point number type. Define cross-module function call chains between modules based on business logic dependencies. Assuming there is another "FileLoader" module responsible for providing the file path, define a cross-module function call chain between the "DataProcessor" module and the "FileLoader" module. The parameter interface passed along with the call chain is the return value (string type) of the "FileLoader.get_file_path()" function passed to the "DataProcessor.read_file_data()" function. The formula for defining the priority of logic unit combination order is:

[0102]

[0103] in: This represents the priority score of the logic unit in the combinational sequence. The weights representing syntactic constraints, The score represents the degree of conformity to grammatical constraints. Weights representing logical dependencies This represents the strength of logical dependencies.

[0104] It is understandable that constraint-driven semantic synthesis engines ultimately encapsulate all organized entities, control nodes, and modules in the form of a graph structure. The generated candidate code abstract semantic graph is a directed acyclic graph, where nodes represent operations, data, or control structures, and edges represent data flow or control flow. This graph structure contains complete syntactic information, logical structure, and architectural layout. It serves as an intermediate representation decoupled from the specific syntax of a programming language, providing unified and rich source code information for subsequent code generators.

[0105] In one embodiment of the present invention, a feedback-based semantic graph optimizer receives candidate code abstract semantic graphs from a constraint-driven semantic synthesis engine. These candidate code abstract semantic graphs contain code logic units, control nodes, and module information encapsulated in a graph structure. In a specific implementation, a graph-to-code converter is configured to translate the nodes and edges in the candidate code abstract semantic graphs into specific code statements in the target programming language according to predefined conversion rules. The graph-to-code converter traverses the nodes of the candidate code abstract semantic graphs, identifying "function definition nodes," "condition judgment nodes," "loop control nodes," and "data flow edges." It converts "function definition nodes" into code statements of the form "deffunction_name(parameter:"), "condition judgment nodes" into "ifcondition:" and "else:" code blocks, and "data flow edges" into variable assignment statements. The conversion process instantiates a preliminary code snippet, for example, converting a semantic graph about file reading and calculating average values ​​into a preliminary code snippet in Python. This preliminary code snippet contains a "read_file_data" function and a "calculate_average" function, along with surrounding conditional logic.

[0106] In some embodiments, a preliminary code snippet is loaded into a lightweight execution sandbox, which includes a restricted runtime environment and a monitor for detecting runtime exceptions. The restricted runtime environment limits file system access permissions, network connectivity, and memory usage limits, providing an isolated execution space for the preliminary code snippet. The monitor for detecting runtime exceptions is embedded in the restricted runtime environment. The monitor intercepts standard library calls and system calls via hook functions and also includes a static analyzer that performs simple type annotation checks before code execution. The preliminary code snippet is then fully loaded into the isolated memory space of the lightweight execution sandbox, ready for execution.

[0107] In some embodiments, an initial code snippet is run, and a monitor used for detecting runtime exceptions captures runtime exceptions, type errors, or logical inconsistencies. A lightweight execution sandbox executes the initial code snippet, simulating a call to the `calculate_average` function with an empty file path passed in. The monitor for detecting runtime exceptions captures a `FileNotFoundError` runtime exception. In another execution, a file containing non-numeric characters is passed in, and the monitor captures a `TypeError` type error when the `sum()` function is executed. The monitor converts the captured `FileNotFoundError` runtime exception and `TypeError` type error into semantic mismatch descriptions for specific nodes or edges in the candidate code abstract semantic graph. These semantic mismatch descriptions explicitly state that "the 'file path string parameter' associated with the 'open() function node' was not validated, resulting in a runtime semantic mismatch," and "the 'iterable object parameter' associated with the 'sum() function node' had its element type unconstrained, resulting in a type semantic mismatch."

[0108] Optionally, the semantic mismatch description is encapsulated into a feedback data packet. This packet uses a structured JSON format and includes the mismatch type, associated entity identifiers, knowledge graph node identifiers, original error information, and context code location. The feedback data packet is sent back to the entity relationship correction stage of the recursive semantic fusion mechanism via network messages or internal function calls. Upon receiving the feedback data packet, the recursive semantic fusion mechanism parses out the entity identifiers "file reading intent" and "average calculation intent" that need to be re-evaluated, instructing the entity relationship correction stage to re-evaluate and adjust the alignment or relationship of the relevant entities. The re-evaluation process references the semantic information in the feedback and may trigger a new round of knowledge graph matching. The formula for evaluating the impact of the feedback on the adjustment is:

[0109]

[0110] in: The amount of change that needs to be adjusted in the weights of entity relationships. It is the learning rate coefficient. This represents the cumulative frequency of semantic mismatches of the same type recorded in the feedback data packet.

[0111] It's understandable that the lightweight execution sandbox operates on an exploratory and diagnostic basis. Its purpose isn't to obtain correct program output, but rather to expose semantic defects in the abstract semantic graph of candidate code by triggering potential execution paths. Similarly, the feedback-based semantic graph optimizer and the recursive semantic fusion mechanism together constitute a closed-loop optimization system. The feedback data packet is the key information carrier connecting code execution verification with high-level semantic alignment, enabling the entire automatic programming generation method to learn from runtime errors and self-correct.

[0112] The above are merely preferred embodiments of the present invention and are not intended to limit the present invention in any other way. Any person skilled in the art may make changes or modifications to the above-disclosed technical content to create equivalent embodiments that can be applied to other fields. However, any simple modifications, equivalent changes, and modifications made to the above embodiments based on the technical essence of the present invention without departing from the scope of the present invention shall still fall within the protection scope of the present invention.

Claims

1. A method for automatically generating programming based on knowledge graphs, characterized in that, The method includes: Construct an initial semantic awareness network and extract the core functional intent entities and data operation entities from it; A recursive semantic fusion mechanism is adopted to iteratively align and fuse the functional intent entities and data operation entities with a pre-built knowledge graph containing programming concepts and domain rules. In each iteration, the boundaries and attributes of the entities are corrected and an intermediate semantic alignment mapping is generated. Based on the intermediate semantic alignment mapping, a multi-level constraint activation process is triggered, which activates the syntactic constraints, logical constraints, and architectural constraints related to the aligned entities from the knowledge graph. Through a constraint-driven semantic synthesis engine, the syntactic constraints, logical constraints, and architectural constraints activated by the multi-level constraint activation process are used as guiding rules to reorganize and connect entities in the intermediate semantic alignment mapping, generating a candidate code abstract semantic graph. Deploy a feedback-based semantic graph optimizer to instantiate the candidate code abstract semantic graph into preliminary code fragments. Verify the preliminary code fragments through a preset lightweight execution sandbox and feed back the semantic mismatch information generated during the verification process to the recursive semantic fusion mechanism to initiate a new round of iterative alignment. The recursive semantic fusion mechanism specifically includes: Each entity in the functional intent entity and data operation entity set is used as a query item in the knowledge graph for preliminary matching to obtain a set of candidate nodes for each entity in the knowledge graph; Analyze the graph relationships between the candidate node sets, and modify and enhance the entity relationships in the functional intent entity and data operation entity sets based on the graph relationships; Based on the corrected entity relationships, the semantic fit between entities and knowledge graph nodes is calculated, the optimal node matching pair is selected, and an intermediate semantic alignment mapping for one iteration is formed. Determine whether there are semantically ambiguous or conflicting entities in the current intermediate semantic alignment mapping. If so, resubmit the relevant entities and their context to the initial semantic perception network for re-analysis and start the next recursive semantic fusion. The deployment of the feedback-based semantic graph optimizer specifically includes: Configure a graph-to-code converter to translate the nodes and edges in the candidate code abstract semantic graph into specific code statements in the target programming language according to predefined conversion rules, thereby instantiating them into preliminary code fragments; The initial code snippet is loaded into a lightweight execution sandbox, which contains a restricted runtime environment and a monitor for detecting runtime exceptions. Run the initial code snippet, capture runtime exceptions, type errors or logical contradictions through the monitor, and convert the error information into a semantic mismatch description of a specific node or edge in the abstract semantic graph of the candidate code; The semantic mismatch description is encapsulated into a feedback data packet and sent back to the entity relationship correction stage of the recursive semantic fusion mechanism, instructing it to re-evaluate and adjust the alignment or relationship of the relevant entities.

2. The method for automatic programming generation based on knowledge graphs according to claim 1, characterized in that, The construction of the initial semantic awareness network specifically includes: The initial semantic awareness network is used to receive and understand unstructured natural language text input by the user that describes programming requirements. Configure a hierarchical text scanner to parse unstructured natural language text input by the user layer by layer, and identify and tag verb phrases, noun phrases and keywords indicating conditions or loops; The layered text scanner identifies verb phrases as potential operation instructions, maps noun phrases as potential data objects or parameters, and establishes a preliminary dependency relationship between verb phrases and noun phrases. By using a domain dictionary to perform semantic disambiguation on the mapped potential operation instructions and potential data objects, each entity is assigned a precise meaning in the programming context, forming a structured set of functional intent entities and data operation entities.

3. The method for automatic programming generation based on knowledge graphs according to claim 2, characterized in that, The process of triggering multi-level constraint activation based on the intermediate semantic alignment mapping specifically includes: The intermediate semantic alignment mapping is analyzed to identify the core entities that have been successfully aligned to the knowledge graph nodes; Starting with the core entity, traverse the relation edges in the knowledge graph, collect all directly related constraint nodes marked as grammatical rules, and form a set of grammatical constraints; In the knowledge graph, find nodes that have an indirect logical implication relationship with the core entity, and transform the logical premises or results represented by the nodes into logical constraints to form a set of logical constraints. From the architecture-level subgraph of the knowledge graph, extract the interface definitions and data flow specifications related to the module or component to which the current core entity belongs, and form a set of architecture constraints.

4. The method for automatic programming generation based on knowledge graphs according to claim 3, characterized in that, The constraint-driven semantic synthesis engine uses the syntactic constraints, logical constraints, and architectural constraints activated by the multi-level constraint activation process as guiding rules to reorganize and connect entities in the intermediate semantic alignment map, generating a candidate code abstract semantic graph, specifically including: Based on the set of grammatical constraints, an expression template and combination order conforming to the grammar of the target programming language are determined for the entities in the intermediate semantic alignment map; Apply the set of logical constraints to insert necessary condition judgment nodes and loop control nodes into the expression template, and determine the effective scope and logical connection relationship of the condition judgment nodes and loop control nodes; Following the set of architectural constraints, the synthesized code logic units are organized into modules or functions that conform to the architectural specifications, and the calling relationships and parameter passing interfaces between modules or functions are defined. The entities, control nodes, and modules, after being organized by syntactic, logical, and architectural constraints, are encapsulated in the form of a graph structure to generate the candidate code abstract semantic graph with a clear structure and executability.

5. The method for automatic programming generation based on knowledge graphs according to claim 4, characterized in that, The process involves using a domain dictionary to perform semantic disambiguation on the mapped potential operation instructions and potential data objects, assigning each entity a precise meaning in the programming context, and forming a structured set of functional intent entities and data operation entities, including: Query the domain dictionary to obtain all possible interpretations of each potential operation instruction in all programming contexts; Query the domain dictionary to obtain all data types and structure definitions corresponding to each potential data object; Based on the preliminary dependency relationship between verb phrases and noun phrases, the programming operation semantics that best match the current context are selected from the possible interpretations; Select data types from the data types and structure definitions that match the semantic requirements of the current programming operation; The selected programming operation semantics are assigned corresponding potential operation instructions to form functional intent entities; The selected data types are assigned to the corresponding potential data objects to form data operation entities; The functional intent entity and the data operation entity are linked according to the preliminary dependency relationship to form a structured set of functional intent entities and data operation entities.

6. The method for automatic programming generation based on knowledge graphs according to claim 5, characterized in that, The process of parsing the intermediate semantic alignment mapping and identifying the core entities that have been successfully aligned to knowledge graph nodes includes: Iterate through all the matching pairs between entities and knowledge graph nodes recorded in the intermediate semantic alignment mapping; Check whether the semantic fit of each matching pair exceeds the preset confidence threshold; The entities corresponding to matching pairs whose semantic fit exceeds the confidence threshold are marked as successfully aligned entities; Filter out the entities with the highest dependency weight in the initial semantic awareness network from the successfully aligned entities; The selected entities are identified as core entities, and the target node identifier corresponding to each core entity in the knowledge graph is recorded.

7. The method for automatic programming generation based on knowledge graphs according to claim 6, characterized in that, The process of organizing synthesized code logic units into modules or functions that conform to the architectural specifications, following the set of architectural constraints, and defining the calling relationships and parameter passing interfaces between modules or functions, includes: Read the module partitioning rules and function encapsulation principles defined in the architecture constraint set; According to the module division rules, code logic units that share a common data source or execute coherent business logic are aggregated into the same module boundary; According to the aforementioned function encapsulation principle, code logic units that complete specific subtasks are encapsulated into independent function units; Based on the interface specifications defined in the set of architectural constraints, generate an external function call entry point for each module; Analyze the data flow between function units within the analysis module, and define the parameter types, parameter order, and return value types required when calling functions based on the parameter passing specifications in the architecture constraint set. Define cross-module function call chains and parameter interfaces that are passed along with the call chains based on business logic dependencies between modules.

8. A knowledge graph-based automatic programming generation system, comprising a memory, a processor, and a computer program stored in the memory and running on the processor, characterized in that, When the processor executes the computer program, it implements the steps of the knowledge graph-based automatic programming generation method described in any one of claims 1 to 7.

Citation Information

Patent Citations

  • Text code generation method based on multi-modal semantic embedding and dynamic knowledge graph

    CN121143767A

  • Cognitive process code generation

    US20190087731A1