A code generation method and system based on a knowledge graph
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-05-12
- Publication Date
- 2026-08-11
AI Technical Summary
但该方法未延伸至代码生成场景,且检索仍依赖精确的文本查询,无法直接适配自然语言驱动的代码生成需求,且多跳依赖检索能力未经过仓库级场景验证
[0059](1)本发明提出项目感知、意图驱动的动态知识图谱增强机制,针对传统静态代码知识图谱离线构建、信息滞后、无法感知项目上下文与用户意图的问题,通过用户意图热度计算实现核心代码实体识别与加权,以高热度实体为锚点完成项目感知局部子图抽取,实现节点轻量化缩容,并利用图神经网络推理实现节点特征更新、隐性依赖链路预测及长程多跳依赖补全,采用不修改原始图谱的增量热更新方式,满足在线代码生成的低延迟要求。
Smart Images

Figure CN122547322A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of software code generation technology, and specifically to a code generation method and system based on knowledge graphs. Background Technology
[0002] As software projects become larger and their business logic more complex, code generation technology, as a core means of improving development efficiency, has evolved from early rule-template-driven methods to generation methods based on large language models. Existing large language models can transform natural language requirements into syntactically correct code snippets, and are widely used in individual development and small-scale projects.
[0003] However, in scenarios such as large-scale team collaborative development, legacy system refactoring, and the construction of complex enterprise applications, code generation technology faces significant challenges: the generated code is no longer an isolated fragment, but needs to be embedded in a complex project architecture, forming tight dependencies with existing code and multi-module components. Existing code generation methods mostly focus on generating single files or short code snippets, lacking a systematic understanding of the target project's global architecture and long-range, multi-hop dependencies across files and modules. This leads to problems such as architectural incompatibility, missing dependencies, incorrect API calls, and redundant development in the generated code, requiring developers to invest a significant amount of time in manual correction, severely impacting development efficiency and code quality.
[0004] Currently, some exploratory research has been conducted on code-related technologies based on knowledge graphs, focusing on core scenarios such as code retrieval, code completion, and code generation, laying the foundation for the development of domain technologies. However, there are still significant limitations in areas such as complex dependency handling, global association capture, and retrieval adaptability to requirements. The specific research status is as follows:
[0005] Reference [1] "Xing Shuangshuang, Liu Mingwei, Peng Xin. Automatic generation method of code semantic tags based on software knowledge graph. Journal of Software, 2022, 33(11):4027-4045." proposes the KGCodeTagger method, which extracts concepts and relationships from API documents and software development question-and-answer texts (such as StackOverflow) to construct a software knowledge graph covering API calls, function descriptions, and scenario constraints, for automatic generation and retrieval assistance of code semantic tags. In the retrieval stage, this method achieves semantic-level retrieval matching through the link of "code entity-graph concept". Compared with the traditional text matching method, the Top-10 retrieval recall rate is improved by 28%. However, it has the following limitations: First, knowledge graphs focus on API-related concepts and direct relationships, and do not cover long-range multi-hop dependency chains of "function-variable-module", so they cannot handle cross-file dependency retrieval needs; Second, retrieval triggers precise matching of dependency code entities or API names, lacks the ability to parse natural language requirements, and cannot respond to unstructured queries such as "implementing an interface for user login status verification and returning a token". Users need to know the specific API or function name, which limits the adaptability of scenarios.
[0006] Reference [2] "Wang Fei, Liu Jingping, Liu Bin, Qian Tieyun, Xiao Yanghua, Peng Zhiyong. Research on code knowledge graph construction and intelligent software development method. Journal of Software, 2020, 31(1):47-66." points out that traditional open domain knowledge graphs cannot directly adapt to the hierarchical organization logic of the code domain (such as the nested relationship of module-file-class-function), and proposes a code knowledge graph modeling framework for software engineering scenarios. This framework extracts entities such as classes, functions, and variables in Java code through the ANTLR syntax parsing tool, mines the direct relationship between entities such as calls and inheritance, and implements structured storage based on the Neo4j graph database. In the retrieval stage, the strategy of "entity attribute matching + direct relationship traversal" is adopted, which improves the semantic relevance of the retrieval results by 32% compared with the traditional text matching method. However, this solution has the following limitations: First, the retrieval scope only covers direct relationships between entities (such as function A calling function B), and cannot handle long-range, multi-hop dependency scenarios such as "function A calls function B, and function B references variable D in module C"; Second, the retrieval triggers dependencies with precise entity names (such as "getUserInfo function"), lacks the ability to parse natural language requirements, and cannot respond to unstructured queries such as "implementing an interface for user login status verification and returning a token". Users need to know the specific code entity information, which limits the adaptability of the scenario.
[0007] Reference [3] "Zhou Guangyou, Xie Qi, Yu Xiao. Code search method based on relational graph convolutional network. Journal of Software, 2024, 35(6):2863-2879." proposes a code retrieval method based on relational graph convolutional network (RGCN). This method constructs a text graph and a code graph, encodes the graph structure through RGCN, and achieves fine-grained matching of text requirements and code fragments at the node layer. The retrieval accuracy is improved by 18% compared with the GraphSearchNet model on public datasets. However, this method has not been extended to code generation scenarios, and the retrieval still relies on precise text queries. It cannot directly adapt to the code generation requirements driven by natural language, and the multi-hop dependency retrieval capability has not been verified in warehouse-level scenarios.
[0008] In summary, existing code knowledge graphs only extract code entities and direct relationships, failing to adequately cover hierarchical organizational logic, long-range dependency chains, and implicit usage patterns, making it difficult to support accurate dependency retrieval in complex scenarios. Furthermore, traditional graph retrieval methods cannot simultaneously handle long-range multi-hop dependency queries, natural language fuzzy retrieval, and efficient execution. Related research also generally suffers from limited dependency coverage, lack of support for natural language-driven requirements, and incompatibility with complex repository-level projects, failing to meet the accuracy, compatibility, and efficiency requirements of enterprise-level code generation. Summary of the Invention
[0009] Purpose of the invention: This invention proposes a code generation method and system based on knowledge graphs, aiming to solve the above-mentioned problems of existing technologies and achieve natural language-driven, project-global dependency-compatible, accurate and efficient enterprise-level code generation.
[0010] Technical solution: A code generation method based on knowledge graphs, comprising the following steps:
[0011] Obtain the original codebase and natural language requirements, and obtain the original knowledge graph corresponding to the original codebase;
[0012] Based on natural language requirements, the original knowledge graph is dynamically enhanced, including: extracting target entities from natural language requirements, extracting local subgraphs centered on the target entities, performing graph neural network inference on the local subgraphs, predicting implicit dependencies between code entities and completing multi-hop dependency paths, and incrementally writing the prediction results into the original knowledge graph to obtain the enhanced knowledge graph.
[0013] Based on natural language requirements, a hybrid retrieval is performed in the augmented knowledge graph to obtain a set of dependency information; the hybrid retrieval includes calculating a dependency complexity score based on natural language requirements and selecting a retrieval strategy based on the dependency complexity score;
[0014] The dependency information set and natural language requirements are input into the code generation model to generate initial code;
[0015] The initial code is validated and optimized, and the target code is output.
[0016] Furthermore, based on natural language requirements, the original knowledge graph is dynamically enhanced, specifically including:
[0017] Entity recognition is performed on natural language requests to extract the target entity set and calculate the intent heat value of each target entity.
[0018] The target entity whose intent heat value meets the preset condition is linked to the corresponding code entity node in the original knowledge graph. The successfully linked code entity node is used as the anchor point. Entity nodes in the original knowledge graph whose shortest hop distance from the anchor point does not exceed the preset maximum hop number are extracted to form a local subgraph.
[0019] The graph convolutional network is used to update node features on local subgraphs. The probability of implicit dependencies between nodes is calculated by the edge prediction decoder. Node pairs with a probability greater than a first preset threshold are identified as implicit dependencies.
[0020] For any two potential multi-hop paths between nodes, calculate the reachability score of the multi-hop path, where the reachability score is the product of the confidence scores of each edge in the multi-hop path; multi-hop paths with reachability scores greater than a second preset threshold are identified as long-range dependent paths.
[0021] The edge sequences corresponding to implicit dependencies and long-range dependency paths are incrementally written into the original knowledge graph. During the incremental writing process, the original nodes and edges are not modified, and dynamic labeling attributes are added to the newly added nodes and edges.
[0022] Further, the intent heat value of each target entity is calculated, specifically including:
[0023] The intent heat value is obtained by weighting the entity name semantic similarity, context matching score and functional intent relevance.
[0024]
[0025] in, The intended popularity value, Semantic similarity of entity names measures the degree of semantic matching between entity names and user request text, reflecting the closeness of the association between the literal expression of the entity and the target of the request. The context matching score is used to evaluate the relevance and adaptability of an entity in the overall context of user needs, and to characterize the degree of collaborative association between the entity and contextual information. Functional intent relevance is used to characterize the degree of fit between an entity and the core functional intent of user needs, and to quantify the supporting value of the entity for the target code function; α, β, and γ are preset weighting coefficients, and the three satisfy α+β+γ=1.
[0026] Furthermore, when extracting local subgraphs, the code entity nodes that are successfully linked are used as the core anchor points. In the original knowledge graph, code entity nodes whose shortest hop count from the core anchor point does not exceed the preset maximum hop count K are included in the local subgraph range, where K is an integer from 1 to 5.
[0027] Project affiliation verification is performed on entity nodes included in the local subgraph. Only entity nodes belonging to the current project are retained, while entity nodes from external libraries and third-party dependencies are filtered out to obtain the local subgraph. The project affiliation mapping is achieved by extracting entity attributes and then performing bidirectional verification matching. After extracting the ID attributes of the project and module, dual verification is performed on the selected candidate entity nodes. The first layer is code package path verification, which extracts the code package path of the candidate entity and matches it with the prefix of the current project's core package path. External package paths are directly identified as noise. The second layer is project identifier and module affiliation verification, which extracts the ProjectID and module ID of the candidate entity and matches them with the corresponding information of the current project. If both verifications pass, the entity is determined to belong to the current project; if either verification fails, the entity is determined to be a non-current project entity. Finally, only entities that pass both verifications and their project associations are retained, while external noise that fails the verification is filtered out.
[0028] Furthermore, based on natural language requirements, hybrid retrieval is performed within the augmented knowledge graph, specifically including:
[0029] The natural language requirements are parsed to generate structured retrieval tasks, which include task type, target entity, relation constraints, and path constraints.
[0030] Perform vector pre-retrieval to convert entities in the augmented knowledge graph into embedding vectors. Based on the similarity between the embedding vector of the target entity and the embedding vectors of each entity in the knowledge graph, filter entities with similarity greater than a preset similarity threshold to obtain a candidate entity set.
[0031] Determine the dependency hop count weight H based on relational constraints, and determine the implicit dependency quantity weight L based on path constraints; calculate the dependency complexity score based on the dependency hop count weight H and the implicit dependency quantity weight L.
[0032] Based on the candidate entity set, when the dependency complexity score is lower than the preset complexity threshold, dynamic graph query planning is used for retrieval; when the dependency complexity score is not lower than the preset complexity threshold, constraint-guided Monte Carlo tree search is used for retrieval. The constraint-guided Monte Carlo tree search introduces code graph-specific heuristic values in the node selection stage, and performs path pre-scoring and pruning based on code structure matching degree and dependency call frequency in the simulation stage.
[0033] Furthermore, dynamic graph query planning retrieval is employed, specifically including:
[0034] Based on the abstract syntax tree, structured retrieval tasks are compiled into logical query plans;
[0035] The logical query plan is transformed into an optimized graph database physical query statement, and the optimization includes index selection optimization and traversal order optimization.
[0036] Execute the physical query statement to extract dependency information.
[0037] Furthermore, constraint-guided Monte Carlo tree search is used to perform the retrieval, specifically including:
[0038] Initialize the search tree with the code entity nodes in the candidate entity set as the root node;
[0039] During the node selection phase, a node value score is calculated based on the node's cumulative value, the number of times the node is accessed, and the code graph-specific heuristic value. The node with the highest value score is selected for expansion. The code graph-specific heuristic value is calculated by weighting code structure matching degree, dependency call frequency, and historical effective path probability.
[0040] The maximum number of search hops is determined based on the dependency complexity score, and the maximum number of search hops is positively correlated with the dependency complexity score;
[0041] During the simulation phase, path pre-scores are calculated based on code structure matching degree, dependency call frequency, and historical effective path similarity. Paths with path pre-scores below the preset pre-score threshold are pruned.
[0042] During the backtracking phase, the path effectiveness score is calculated based on the matching degree between the path and the demand intent, the correlation degree of the path entities, and the rationality of the relationship. The cumulative value and access count of each node are then updated in reverse along the search path.
[0043] When a path with a validity score greater than a preset validity threshold is found, the search stops and dependency information is output.
[0044] Furthermore, the initial code is validated and optimized, including:
[0045] The initial code undergoes syntax verification, which includes static syntax parsing and dynamic compilation verification. When syntax errors are detected, a correction scheme is automatically generated and the initial code is corrected.
[0046] Dependency checks are performed on the corrected initial code based on the augmented knowledge graph. The dependency checks include: checking whether the entity called in the code exists in the augmented knowledge graph. If it does not exist, similar entities are recommended and corrected based on the knowledge graph; checking whether the entity called is an obsolete entity. If it is, alternative entities are recommended and corrected; checking whether the code's dependency version, parameter type, and return value type are compatible with existing entities. If they are not compatible, type adjustments or conversions are performed.
[0047] When a dependency is found to be missing or conflicting during the verification process, a secondary hybrid search is triggered to complete the dependency information, and the code is regenerated based on the completed dependency information.
[0048] Based on the usage pattern relationships in the augmented knowledge graph, the code that passes the dependency verification is structurally optimized. The structural optimization includes: adjusting variable names, function names, and class names according to the naming conventions in the knowledge graph; optimizing the function call order and variable declaration position, and deleting unused variables and duplicate code snippets; optimizing code performance based on the usage frequency of entities in the knowledge graph; and adding comments to the code based on entity annotations and requirement intents in the knowledge graph.
[0049] A knowledge graph-based code generation system includes:
[0050] The data acquisition module is used to acquire the original codebase and natural language requirements, and to acquire the original knowledge graph corresponding to the original codebase.
[0051] The knowledge graph enhancement module is used to dynamically enhance the original knowledge graph according to natural language requirements. This includes: extracting target entities from natural language requirements, extracting local subgraphs centered on the target entities, performing graph neural network inference on the local subgraphs, predicting implicit dependencies between code entities and completing multi-hop dependency paths, and incrementally writing the prediction results into the original knowledge graph to obtain the enhanced knowledge graph.
[0052] The hybrid retrieval module is used to perform hybrid retrieval in the augmented knowledge graph according to natural language requirements to obtain a set of dependency information; the hybrid retrieval includes calculating a dependency complexity score according to natural language requirements and selecting a retrieval strategy based on the dependency complexity score;
[0053] The code generation module is used to input the dependency information set and natural language requirements into the code generation model to generate initial code;
[0054] The results optimization module is used to verify and optimize the initial code and output the target code.
[0055] The present invention also provides an electronic device, comprising: a processor; a memory; and a computer program, the computer program being stored in the memory and configured to be executed by the processor, the computer program, when executed by the processor, implementing the knowledge graph-based code generation method as described above.
[0056] The present invention also provides a computer-readable storage medium having a computer program stored thereon, wherein the computer program, when executed by a processor, implements the knowledge graph-based code generation method described above.
[0057] The present invention also provides a computer program product, including a computer program that, when executed by a processor, implements the knowledge graph-based code generation method described above.
[0058] Beneficial effects:
[0059] (1) This invention proposes a dynamic knowledge graph enhancement mechanism based on project perception and intent-driven approach. It addresses the problems of offline construction, information lag, and inability to perceive project context and user intent in traditional static code knowledge graphs. It achieves core code entity identification and weighting through user intent heat calculation, extracts local subgraphs for project perception using high-heat entities as anchors, realizes lightweight scaling of nodes, and uses graph neural network inference to achieve node feature updates, implicit dependency link prediction, and long-range multi-hop dependency completion. It adopts an incremental hot update method that does not modify the original graph, meeting the low latency requirements of online code generation.
[0060] (2) The present invention designs a three-stage adaptive routing hybrid retrieval strategy. First, the fuzzy natural language requirements are transformed into structured retrieval tasks through multi-granularity requirement analysis. The three-stage retrieval process is combined with vector pre-retrieval, adaptive routing decision, dynamic graph query planning and CG-MCTS. The retrieval strategy is dynamically selected according to the dependency complexity, query clarity and candidate entity size. Simple dependencies use fast graph query and complex dependencies use constraint-guided Monte Carlo tree search. It can accurately mine explicit dependencies, implicit dependencies and long-range multi-hop dependencies at the same time, taking into account retrieval efficiency and dependency mining completeness.
[0061] (3) This invention proposes a structured code generation method based on dependency injection. The project dependencies, structural specifications and calling relationships obtained by mixed retrieval are injected into the code generation process through structured prompt words to guide the model to generate code that fits the project context. After generation, syntax verification and iterative correction are automatically performed to ensure that the output code conforms to the project architecture and syntax specifications, effectively solving the problems of isolated generation and poor compatibility of traditional code generation.
[0062] (4) This invention constructs a three-level verification and automatic correction result optimization closed loop. Through the three-level quality assurance mechanism of syntax verification, dependency consistency verification, code structure and standardization optimization, it comprehensively detects and optimizes syntax errors, missing / conflicting / obsolete dependencies, naming conventions, code structure, performance and comment integrity. When missing or conflicting dependencies are detected, it automatically checks back and triggers a secondary search to complete the dependencies, forming a quality closed loop, and finally outputs usable code that can be directly integrated and used. Attached Figure Description
[0063] Figure 1 System architecture diagram;
[0064] Figure 2 Flowchart of the mechanism for enhancing project awareness of dynamic knowledge graphs;
[0065] Figure 3 This is a flowchart of a three-stage adaptive routing hybrid retrieval process;
[0066] Figure 4 A flowchart for code generation and optimization. Detailed Implementation
[0067] The technical solutions in the embodiments of the present invention will now be clearly and completely described in conjunction with the accompanying drawings.
[0068] Figure 1 The overall system architecture of this invention is illustrated, comprising an input layer, four core functional modules, and an output layer. These modules work together to transform natural language requirements into high-quality target code. The four core functional modules are: a knowledge graph enhancement module, a three-stage adaptive routing hybrid retrieval module (hereinafter referred to as the hybrid retrieval module), a code generation module, and a result optimization module. The structural design, functional division, and interaction logic of each module are as follows:
[0069] Input Layer (Data Acquisition Module): Receives two types of core inputs. The first is the user's natural language requirements (such as "Implement an interface that calls the user module's getUserInfo function and returns user details"), supporting various forms such as unstructured descriptions and semi-structured requirement documents. The second is the original code library, which contains multi-file and multi-module source code of the target project (supporting mainstream programming languages such as Java, Python, and C++), as well as auxiliary information such as project configuration files and API documentation.
[0070] Among the core functional modules, the knowledge graph enhancement module, driven by intent and project awareness, performs lightweight dynamic enhancement of the global code graph, outputting low-latency project-level semantic knowledge adapted to the current task; the three-stage adaptive routing hybrid retrieval module automatically parses requirements and dynamically selects retrieval strategies, accurately mining explicit, implicit, and long-range multi-hop dependencies, providing a reliable basis for code generation; the code generation module integrates dependency information and requirements, generating initial code that conforms to the project architecture and specifications based on the three-stage adaptive routing hybrid retrieval QwenCode, and completing basic syntax verification; the result optimization module forms a quality closed loop through three-level verification and automatic correction, outputting compliant and usable code that can be directly integrated, and triggering back-checking and regeneration in case of anomalies.
[0071] Output layer: Outputs target code that conforms to the project architecture, is syntactically correct, and logically complete. It can be directly integrated into the original code repository without additional manual correction or only requires minor adjustments.
[0072] The interaction logic of each module is as follows: The input layer passes the original code library to the knowledge graph enhancement module and simultaneously passes the natural language requirements to the requirement parsing unit of the three-stage adaptive routing hybrid retrieval module; after completing the graph construction, the knowledge graph enhancement module stores it in the graph database and provides a retrieval interface to the three-stage adaptive routing hybrid retrieval module; the three-stage adaptive routing hybrid retrieval module first parses the natural language requirements to generate a retrieval task, then queries the knowledge graph through the retrieval interface, and outputs the dependency information set to the code generation module; the code generation module combines the requirement intent and dependency information to generate initial code and passes it to the result optimization module; if dependency information is found to be missing or conflicting during the optimization process, the result optimization module will feed back to the three-stage adaptive routing hybrid retrieval module, triggering a secondary retrieval to complete the dependencies, forming a closed-loop interaction, and outputting the final target code to the output layer after optimization.
[0073] The following describes the detailed technical solutions for the core functional modules.
[0074] I. Project-Aware Dynamic Knowledge Graph Enhancement Mechanism
[0075] Existing code knowledge graphs are typically generated once during the code ingestion / build phase, and are therefore static graphs. They suffer from incomplete relational coverage and insufficient depth, failing to provide accurate dependency support for complex code generation. To address this, this invention proposes a project-aware dynamic knowledge graph enhancement mechanism, defining the dynamic enhancement objectives as follows: given an existing global knowledge graph G=(V,E) in the codebase, where V is the set of nodes and E is the set of edges; user natural language requirements Q; and project structure information P. The incrementally enhanced graph is then calculated. The constraints are: no modification to the original graph; enhancement only to local regions relevant to the current task; inference latency less than 200ms; and the ability to complete implicit dependencies, multi-hop dependencies, and project pattern dependencies.
[0076] like Figure 2 As shown, a fixed and reproducible technical route is adopted, and the entire code generation process is embedded online: First, through intent perception and entity weighting, core entities are extracted from demand Q and intent heat is calculated. Then, based on project perception, local subgraph extraction is completed. Local subgraphs within the project are extracted with high-heat entities as the center. Subsequently, GNN incremental inference and completion are carried out on the local subgraphs, and feature updates, link prediction and multi-hop completion are performed. Finally, the newly added nodes and relationships are written into the graph database to complete incremental graph fusion and retrieval openness, forming a heat-enhanced graph.
[0077] (1) Intent perception and intent heat calculation
[0078] First, domain-specific entity recognition (NER) is performed on the user's natural language requirements to extract entity objects that are strongly related to the code generation task, forming a target entity set. ,in This represents the i-th code domain entity identified in the requirements, where n is the total number of entities. Based on this entity set, for each entity... Calculate the intention heat , The value range is normalized to [0,1], and it is used to quantify the importance and association weight of the entity to the current code generation task. The formula for calculating intent heat is:
[0079]
[0080] in: Semantic similarity of entity names measures the degree of semantic matching between entity names and user request text, reflecting the closeness of the association between the literal expression of the entity and the target of the request. The context matching score is used to evaluate the relevance and adaptability of an entity in the overall context of user needs, and to characterize the degree of collaborative association between the entity and contextual information. Functional intent relevance is used to characterize the degree of alignment between an entity and the core functional intent of user needs, quantifying the supporting value of the entity for the target code functionality. α, β, and γ are preset weighting coefficients, satisfying α+β+γ=1 (weighting coefficients). They are used to adjust the contribution weights of entity name semantics, contextual information, and functional intent to the final popularity value, and can be adaptively adjusted according to the code generation task scenario.
[0081] Specifically, The cosine similarity is calculated between entity names and user natural language requests after semantic encoding within the code domain. Code-domain pre-trained models (CodeBERT / CodeT5) are used to perform code-domain pre-training on entity names. The entire sentence containing the user's natural language requirement is Q-encoded to obtain a vector:
[0082]
[0083] Calculate cosine similarity The result is already in [−1,1], so we can directly shift and normalize it to [0,1]: .
[0084] The cosine similarity is calculated by semantically encoding the neighborhood context information of an entity in the knowledge graph with the user's natural language requirements. It is extracted from the global knowledge graph G. The set of neighboring nodes is concatenated to form the context description text. Similarly, the encoded vector is obtained: Similarly, using cosine similarity + normalization: .
[0085] The relevance score is calculated by semantic encoding or set matching between entity function tags and user requirement function intents. Code function intent is extracted from user requirement Q to obtain a set of function intent phrases. Examples include "data parsing," "anomaly detection," "concurrency security," and "interface authentication." This involves reading entities from the knowledge graph G. Predefined / automatically labeled functional attribute tags (e.g., "serialization", "log printing", "network requests"). For each... and Perform semantic encoding to obtain the functional intent vector. and entity function vector The similarity was calculated to obtain: .
[0086] Furthermore, entity classification is performed based on the calculated intent heat value, for example, Entities with a value ≥ 0.9 are identified as core entities and used as core anchor points for subsequent local subgraph extraction; entities with a value ≤ 0.6 are identified as core entities. Entities with a value less than 0.9 are considered related entities and included in the scope of task-related information. Entities with a value <0.6 are considered irrelevant and are directly filtered out to remove noise interference.
[0087] (2) Project-aware local sub-graph extraction
[0088] Using high-profile core entities as anchor points, extract local sub-graphs within the project from the global graph. .
[0089]
[0090] K represents the shortest number of hops on the knowledge graph; K represents the maximum number of hops; only entities within the current project are retained, and external library noise is filtered out. It is the set of nodes in the local subgraph, that is, the entity nodes that are selected from the global graph, are related to the current task, and belong to the target project. The set of edges in a local subgraph, i.e., the connection The middle node is a relation edge that also belongs to the target project.
[0091] Local subgraph extraction achieves efficient scaling down of the global graph, accurate adaptation to project scenarios, and real-time assurance for subsequent GNN inference through multi-dimensional range constraints and noise filtering. Specifically, to achieve efficient scaling down from millions to hundreds of nodes, this invention employs a dual screening mechanism of "association filtering + project affiliation mapping." The association filtering is implemented using hop count constraints, setting a maximum hop count K (typically 1-5). Based on the formula dist(v,u)≤K, associated nodes within a K-hop range surrounding the core entity are extracted from the global graph. This allows the subgraph to focus on the core logical links related to the task, eliminating loosely associated long-tail nodes. Project affiliation mapping is achieved by extracting entity attributes and then performing bidirectional verification matching. First, all entity nodes in the global knowledge graph are pre-set with relevant attribute tags such as project affiliation identifier (ProjectID) and code package path. At the same time, basic information such as the core package path prefix and unique ProjectID of the current target project are read as the judgment criteria. Then, the candidate entity nodes after hop count filtering are subjected to double verification. The first layer is code package path verification, which extracts the code package path of the candidate entity and matches it with the core package path prefix of the current project. External package paths are directly judged as noise. The second layer is project identifier and module affiliation verification, which extracts the ProjectID and module ID of the candidate entity and matches them with the corresponding information of the current project. If both verifications pass, it is determined to belong to the current project. If either verification fails, it is determined to be an entity that does not belong to the current project. Finally, only entities that pass both verifications and their association with the project are retained, and external noise that fails the verification is filtered out.
[0092] Through collaborative filtering, precise local regions directly related to the current code generation task and project are extracted, ultimately reducing the graph size from millions to hundreds of lightweight local subgraphs. This process preserves the closely related business logic surrounding the core entities while completely eliminating irrelevant noise from external libraries, achieving precise compression of the graph size and providing high-quality data input for subsequent low-latency GNN inference. This significantly reduces the computational complexity and power consumption of GNN inference, shortening inference time.
[0093] (3) Node feature update
[0094] This invention employs a Graph Convolutional Network (GCN) to perform multi-layer message passing and feature aggregation operations on the extracted local subgraphs, achieving deep enhancement and updating of node semantic features. Specifically, this is accomplished through a hierarchical feature propagation formula:
[0095]
[0096] in This represents the feature vector of node u at the l-th layer, used to characterize the semantic information of the node at the current layer; This represents the set of neighboring nodes of node u in the code knowledge graph. The neighbor relationships cover the calling relationship, reference relationship, containment relationship and inheritance relationship between code entities, and comprehensively cover the core association types at the code structure level. The aggregation function can be selected based on task requirements, such as mean aggregation, summation aggregation, or attention-weighted aggregation, to achieve standardized fusion of neighbor node features; || represents the feature concatenation operation, used to fuse the node's own features with the aggregated neighbor features to form a richer joint feature representation. σ is the activation function, which can be ReLU or GELU, introducing non-linear expressive power into feature propagation and improving the model's ability to model complex code semantics; is the learnable weight matrix of the l-th layer network, used to realize the linear transformation and dimension mapping of feature vectors, and continuously optimize the expressive ability of node features during iterative propagation.
[0097] This reasoning process enables each code entity node to fully absorb the structural and semantic information of surrounding related nodes through multi-layer message passing within the local subgraph. It transforms isolated single node features into project-level semantic representations with project context awareness, effectively alleviating the semantic sparsity problem caused by incomplete information in single entities and enhancing the overall expressive power of node features for project structure, code logic, and dependencies.
[0098] (4) Implicit Dependency Link Prediction
[0099] This invention constructs a dedicated edge prediction decoder to achieve intelligent mining and prediction of implicit dependency links between code entities. It is used to determine whether there are missing implicit dependencies between any two entity nodes u and v that are not captured by traditional static graphs. The probability of edge existence is calculated using the following formula:
[0100]
[0101]
[0102] in, and These represent the semantic feature vectors of entity nodes u and v after incremental reasoning, respectively, which are used to carry the entity's own and project-level context aggregation information; For feature vectors The transpose of the matrix is used to perform linear matching operations between eigenvectors; is the learnable weight matrix of the edge prediction decoder, used to model the nonlinear mapping of relationships between entities, and autonomously learns the intrinsic patterns of code dependencies during training; b is the bias term, used to improve the fitting accuracy and model adaptability of probability prediction. The Sigmoid activation function is used to normalize the prediction results and map them to the [0,1] probability interval, which intuitively represents the confidence level that there is an implicit dependency between entities; Let be the predicted probability value indicating an implicit dependency between entity u and entity v. Set the probability discrimination threshold τ = 0.85. When the predicted probability... If the value is greater than or equal to this threshold, a high-confidence implicit dependency is determined to exist between entities u and v. This dependency is then represented as a triple. Include the incremental edge set, where r is the predicted type of implicit dependency.
[0103] Through the above reasoning process, it can intelligently predict and mine a variety of deep implicit dependencies that traditional abstract syntax trees (ASTs) cannot capture. These include data flow dependencies during code execution, proprietary calling patterns formed over a long period within the project, implicit parameter passing relationships between code files, and implicit exception handling and resource call dependencies in the code logic, thereby effectively filling the information gaps in traditional static code knowledge graphs.
[0104] (5) Long-range multi-hop dependency completion
[0105] Traditional static code knowledge graphs, limited by their construction patterns, can only capture short-range relationships of 1-2 hops between entities, failing to cover deep long-range dependencies within code logic. This invention leverages the multi-layer message passing characteristics of Generative Neural Networks (GNNs) to automatically identify and complete long-range multi-hop dependencies, overcoming the limitations of traditional graph dependency capture. To accurately measure the reliability of multi-hop paths between entities, a multi-hop reachability score formula is defined:
[0106]
[0107] in The reachability score of the multi-hop path between entity node u and entity node v is used to quantify the overall confidence level of the multi-hop path. The higher the score, the higher the confidence level of the long-range dependency between u and v. T represents the total number of edges in the multi-hop path, corresponding to the number of hops of the multi-hop dependency. This mechanism focuses on completing long-range paths with 4 to 5 hops, i.e., T takes the value of 4 to 5. This represents the confidence level of the k-th edge in the multi-hop path. This confidence level comes from the inference result of the implicit dependency link prediction step mentioned earlier (i.e. The confidence level of an edge can be either the original explicit edge confidence level in the global graph or the edge confidence level in the graph itself, used to characterize the reliability of a single edge.
[0108] A preset multi-hop reachability score threshold is set. For any entity pair u and v, the reachability score is calculated for each potential multi-hop path. If the score of a multi-hop path is higher than the preset threshold, the path is determined to be a reliable long-range dependency path. The entire path is incrementally written into the knowledge graph in the form of continuous association, eventually forming a complete long-range dependency relationship of 4 to 5 hops, such as "function A → function B → variable C → module D". This solves the shortcomings of traditional static graphs in capturing long-range dependencies, improves the association integrity of the code knowledge graph, and allows the graph to reflect the deep logical dependencies between codes more comprehensively and accurately.
[0109] (6) Incremental map fusion and hot update
[0110] This invention uses the incremental entity set output by GNN incremental inference. With incremental edge set The knowledge graph is written to the graph database using a hot-insertion method to complete incremental fusion and dynamic updates, ultimately generating an enhanced knowledge graph tailored to the current code generation task.
[0111]
[0112] in, This represents the dynamically enhanced knowledge graph after fusion, where V is the set of basic nodes in the original global knowledge graph. E represents the set of entity nodes added through intent perception and GNN incremental reasoning, and E represents the set of basic relations in the original global knowledge graph. This is the set of newly added dependency edges obtained through implicit dependency prediction and long-range multi-hop completion.
[0113] Incremental writing and hot updates follow strict rules: First, the integrity and immutability of the original graph data are maintained, with no modification, overwriting, or deletion of any node or edge data in the original graph throughout the process, ensuring the stability and usability of the basic graph; Second, all newly added incremental entities and edges are uniformly dynamically marked and labeled with heat, with the label attribute dynamic=TRUE configured to distinguish between original static data and dynamically enhanced data, and heat_score=w i The intent heat value corresponding to the entity is synchronously bound to the incremental data to enhance the traceability and filtering of information.
[0114] Two- and three-stage adaptive routing hybrid retrieval
[0115] This system uses a multi-granularity requirement parsing module and a three-stage adaptive routing hybrid retrieval module to collaboratively transform natural language requirements into efficiently searchable information. The three-stage adaptive routing hybrid retrieval module is the core retrieval unit, responsible for the accurate and efficient mining of dependency information.
[0116] like Figure 3 As shown, the multi-granularity requirement parsing module transforms fuzzy, colloquial natural language requirements into standardized, structured retrieval tasks, providing clear input for subsequent dependency retrieval. The three-stage adaptive routing hybrid retrieval module, based on the parsed retrieval tasks, mines complete dependency information corresponding to the requirements through a three-stage process of vector pre-retrieval, adaptive routing decision, and hybrid retrieval (dynamic graph query planning + CG-MCTS).
[0117] (1) Multi-granularity requirement analysis module
[0118] To address the issues of vague and non-standard natural language requirements, standardized retrieval tasks are output, providing accurate input for the three-stage retrieval process. The steps are as follows:
[0119] Step 1, Preprocessing: Clean the input natural language requirements, segment the words, and tag the parts of speech. Based on the code domain dictionary (including programming language keywords, function names, API names, etc.), standardize the terminology and unify the expression specifications.
[0120] Step 2, Hierarchical Intent Parsing: Using a fine-tuned BERT enhanced model, core intents such as function implementation and dependency calls are extracted, and ambiguous intents are supplemented through common sense reasoning from code knowledge graph;
[0121] Step 3, Enhanced Entity Recognition and Linking: Use a NER model that integrates code semantics to extract target entities (modules, functions, variables, etc.) from the requirements.
[0122] Step 4: Retrieval Task Generation and Error Correction: Based on the parsed intent and entities, generate a structured retrieval task containing "task type, target entity, relation constraints, and path constraints", automatically correct erroneous constraints, complete fuzzy constraints, and output the final retrieval task.
[0123] (2) Three-stage adaptive routing hybrid retrieval
[0124] Phase 1: Vector pre-retrieval quickly filters out entity nodes irrelevant to the requirements, generating a high-quality candidate entity set. In practice, firstly, all entities in the code knowledge graph are uniformly converted into 128-dimensional embedding vectors to capture their deep semantic information. Then, based on the target entities extracted by the multi-granularity requirement parsing module, their corresponding embedding vectors are obtained, and the cosine similarity formula is used to calculate the similarity between this vector and all entity vectors in the knowledge graph. Finally, a similarity threshold is set to filter out irrelevant nodes below this value, forming the final candidate set, effectively reducing computational redundancy and noise interference in subsequent retrieval.
[0125] Phase 2: Adaptive Routing Decision. Based on the specific characteristics of the retrieval task, the most efficient retrieval strategy is dynamically selected to achieve an optimal balance between retrieval efficiency and the completeness of dependency mining. During execution, three core metrics are first calculated: dependency complexity score, query explicitness, and candidate entity size. Among these, query explicitness... This was calculated based on the ratio of explicit commands to vague expressions in user queries. = Number of explicit command words / (Number of explicit command words + Number of fuzzy expressions, value range [0,1]); Candidate entity size The dependency complexity score is obtained by normalizing the number of valid entities in the current task after project affiliation filtering (value range [0,1]); The weights are derived from the weights of dependency hop count and implicit dependency count using a weighted formula. The value range is [0,1]. H is the dependency hop weight, for example, 1 hop = 0.2, 2 hops = 0.5, 3 hops and above = 1.0; L is the implicit dependency weight, for example, no implicit dependency = 0, 1-2 dependencies = 0.3, 3 dependencies and above = 0.7. , These are the weighting coefficients. ,For example , .
[0126] The system then makes a comprehensive judgment based on the above three core indicators and dynamically selects a retrieval strategy: when ≥0.7、 ≥0.6 and When the variance is ≤0.5, a graph query strategy is adopted to accurately discover complex relationships such as multi-hop dependencies and implicit dependencies, ensuring the completeness of dependency mining; when... <0.5 <0.6 and When the index is ≥0.6, a tree query strategy (CG-MCTS) is adopted to quickly filter a large number of candidate entities and improve retrieval efficiency. When the three indicators are in the middle range, a hybrid routing mode is enabled. Tree queries are used to filter core candidate entities and graph queries are used to deeply mine key dependencies, further optimizing retrieval efficiency and dependency mining effect. This ensures that the retrieval process fits the code logic and business needs of the current project and provides accurate retrieval support for subsequent dependency completion and dynamic updates.
[0127] Phase 3: Hybrid Search
[0128] The graph query strategy employs dynamic graph query planning, directly translating logical intent into precise execution statements. First, based on an Abstract Syntax Tree (AST), the structured retrieval task is compiled into a clear logical query plan, clearly defining the target entities and their relationships. Then, the logical plan is automatically transformed into optimized Cypher physical query statements, with the system intelligently selecting the optimal index and optimizing the traversal order. Finally, the query is executed, efficiently extracting simple dependency information with 1-2 hops and outputting retrieval results with a default confidence level (e.g., 0.95), ensuring both speed and accuracy in simple dependency retrieval.
[0129] CG-MCTS (Constraint-Guided Monte Carlo Tree Search) upgrades traditional MCTS to a constraint-guided search for in-depth mining of long-range multi-hop and implicit dependencies. At the beginning of the search, the target entity in the candidate entity set is selected as the root node. The cumulative value and visit count of the root node are initialized to build the foundation of the search tree. Then, the node selection phase begins, with the node selection formula as follows:
[0130]
[0131] To constrain the value score of the guiding node, the highest-scoring node is selected for the next expansion step; Accumulate value for a node, which is the sum of scores for all valid paths passing through that node; This represents the total number of times the current node has been accessed. The current node's parent node has been visited a total of times; C is the exploration coefficient, for example, C= , used for the exploration and utilization of balancing algorithms; γ is the heuristic function weight, for example, taking the value γ=0.3; This is a heuristic value specific to the code graph, ranging from [0,1]. It is specifically calculated by weighting code structure matching degree, dependency call frequency, and historical effective path probability. Code structure matching degree extracts the code structure features of the current node and the target project from the global code knowledge graph, calculating feature similarity as the first weight. Dependency call frequency is calculated by counting the number of times the current node is associated with the target task in historical searches; the more times and the closer the association, the higher the score, serving as the second weight. Historical effective path probability is calculated based on the matching success rate between the node and the target task in past searches, determining its reliability, serving as the third weight. The final result is obtained by weighted summation of these three indicators. The specific values provide precise prior guidance for node selection. The system will prioritize expanding the nodes with the highest value.
[0132] Subsequently, CG-MCTS performs path scoring and selection based on the selected nodes. First, a path value pre-scoring is performed, using the following formula:
[0133]
[0134] The path is pre-scored, with a value range of [0,1], and is used to predict the value of the path before searching. Code structure matching degree represents the degree of fit between the path and the target code structure; Dependency call frequency represents the frequency with which dependencies appear in the codebase within a given path. The similarity to historical effective paths represents the degree of matching between the current path and historical high-value effective paths; the values of the three sub-items can be obtained by summing the corresponding parameters of each node on the path.
[0135] Pruning is performed based on the pre-scoring, for example ≥0.7 Preserve the path; If the hop count is less than 0.7, prune the branch directly to remove invalid search branches. Then apply a dynamic hop count constraint, as shown in the following formula:
[0136]
[0137] The algorithm's traversal depth is automatically limited to the maximum number of search jumps allowed dynamically. The dependency complexity score, already calculated in Phase 2, is then used for targeted simulation, as shown in the following formula:
[0138]
[0139] in, The final path validity score, with a value range of [0,1], is used to comprehensively evaluate the overall quality of the retrieval path. , , With fixed weight coefficients, all parameters are calculated based on the attributes of the CG-MCTS retrieval base tree and the data from the preceding modules. Among them, the path-to-intent matching degree... Based on the features of all entity nodes contained in the path of the basic tree, a cosine similarity is calculated between the cosine similarity and the user demand semantic feature vector output by the pre-intent perception module. The similarity result is the result of this calculation. The value ranges from [0,1]. A higher similarity indicates a greater match between the path and the user's natural language needs. Path Entity Relationship To extract the relationships (explicit dependencies + implicit dependencies) of all entity nodes along this path in the base tree, the total number of direct and indirect relationships between entities along the path is counted, and then normalized by combining the path length (hop count). Total number of entity associations within the path / total number of hops in the path, ranging from [0,1]. A higher value indicates a stronger association between code entities within the path. Relationship rationality. Based on all dependencies (explicit edges + predicted implicit edges) contained in the path of the basic tree, and in conjunction with the code domain syntax specifications and the dependency invocation rules of the current project, the compliance of the dependencies in the path is calculated; simultaneously, this is combined with the implicit dependency chain prediction step mentioned earlier. (Probability of dependency existence), supplemented by the average confidence score of all dependencies, and finally obtained by weighted summation. The value ranges from [0,1]. The higher the value, the stronger the compliance and effectiveness of the code dependency relationship in the path. A path with a value ≥0.9 is considered optimal, and the algorithm stops searching. Simultaneously, incremental pruning is enabled.
[0140]
[0141] The dynamic pruning threshold is adaptively adjusted during the iteration process. This represents the current number of iterations the algorithm has performed. This represents the maximum number of iterations for the algorithm.
[0142] Finally, a backtracking update is performed, inverting the path validity score to update all nodes, and iterating until completion, outputting complex dependency retrieval results with a default confidence level (e.g., 0.92).
[0143] III. Code Generation Module: Structured Dependency Injection and Precise Generation
[0144] The core objective of this module is to deeply integrate dependency information with natural language requirements, and through a structured suggestion injection mechanism, guide the generative model to generate code that conforms to the project architecture, dependency relationships, and usage patterns.
[0145] In this embodiment of the invention, the Qianwen Big Model is selected as the basic generation model, and fine-tuned and optimized for repository-level code generation scenarios. During the code generation phase, the model generates code based on prompts, including a complete structure such as import statements, interface / class definitions, function implementations, and variable declarations. During the syntax verification phase, the corresponding programming language's syntax parser (such as javac for Java or pyflakes for Python) is called to perform syntax verification on the generated code. If syntax errors are found, they are fed back to the model for correction.
[0146] IV. Results Optimization Module: Closed-Loop Validation and Quality Improvement
[0147] By performing syntax validation, dependency verification, and code structure optimization, the quality and usability of the generated code are improved, ensuring that the code can be directly integrated into the original codebase. It includes submodules for syntax validation, dependency verification, and code structure optimization, as detailed below:
[0148] (1) Syntax Validation Submodule: Comprehensive Syntax Error Detection and Correction
[0149] A dual verification strategy of static syntax parsing and dynamic compilation verification is employed to ensure that the generated code is free of syntax errors. Static syntax parsing calls the corresponding programming language's syntax parser to parse the generated code, detect syntax errors, and locate the error locations. Dynamic compilation verification compiles the generated code together with relevant files from the original codebase (e.g., Java code is compiled using Maven, and Python code undergoes syntax checking) to detect compilation errors. For detected errors, correction schemes are automatically generated, such as automatically adding parentheses when they are mismatched, and adding import paths based on the package to which the entity belongs in the knowledge graph when import statements are missing.
[0150] (2) Dependency Validation Submodule: Consistency Validation of Dependencies
[0151] Based on a code knowledge graph, the system verifies the consistency of dependencies between the generated code and existing projects, avoiding missing dependencies, dependency conflicts, or calls to deprecated entities. This includes: Dependency Existence Verification: Checking if entities such as functions called, variables referenced, and implemented interfaces in the generated code exist in the code knowledge graph. If not, similar entities are recommended and corrected based on the knowledge graph; Dependency Validity Verification: Checking if called entities are deprecated (e.g., functions marked @Deprecated). If deprecated entities are called, alternative entities are recommended and the code is corrected; Dependency Compatibility Verification: Checking if the dependency versions, parameter types, and return value types of the generated code are compatible with existing entities. If incompatible, parameter types are automatically adjusted or type conversions are performed. If missing or conflicting dependencies are found, feedback is sent to the three-stage adaptive routing hybrid retrieval module, triggering a secondary retrieval to complete the dependencies and ensure the completeness of dependencies in the generated code.
[0152] (3) Structure optimization submodule: code standardization and performance optimization
[0153] Based on usage patterns and project guidelines within the code knowledge graph, the generated code undergoes structural optimization to improve maintainability and performance. This includes: adjusting variable, function, and class names according to naming conventions in the knowledge graph to ensure compliance with project naming standards; optimizing function call order and variable declaration locations, and simplifying redundant code, such as deleting unused variables and merging duplicate code snippets; optimizing code performance based on entity usage frequency and performance data in the knowledge graph, such as prioritizing high-performance utility functions and avoiding frequent creation of temporary variables; and adding comments to the generated code based on entity annotations and requirement intents in the knowledge graph to improve maintainability.
[0154] Code generation and optimization process as follows Figure 4 As shown.
[0155] The system of this invention adopts a layered architecture design of input layer - four core functional modules - output layer. Each module has clear interfaces, clear division of labor, and fixed interaction process, and has deployability and reproducibility.
[0156] Accordingly, this invention provides a code generation method based on knowledge graphs, comprising the following steps:
[0157] Obtain the original codebase and natural language requirements, and obtain the original knowledge graph corresponding to the original codebase;
[0158] Based on natural language requirements, the original knowledge graph is dynamically enhanced, including: extracting target entities from natural language requirements, extracting local subgraphs centered on the target entities, performing graph neural network inference on the local subgraphs, predicting implicit dependencies between code entities and completing multi-hop dependency paths, and incrementally writing the prediction results into the original knowledge graph to obtain the enhanced knowledge graph.
[0159] Based on natural language requirements, a hybrid retrieval is performed in the augmented knowledge graph to obtain a set of dependency information; the hybrid retrieval includes calculating a dependency complexity score based on natural language requirements and selecting a retrieval strategy based on the dependency complexity score;
[0160] The dependency information set and natural language requirements are input into the code generation model to generate initial code;
[0161] The initial code is validated and optimized, and the target code is output.
[0162] The present invention also provides an electronic device, comprising: a processor; a memory; and a computer program, the computer program being stored in the memory and configured to be executed by the processor, the computer program, when executed by the processor, implementing the knowledge graph-based code generation method as described above.
[0163] The present invention also provides a computer-readable storage medium having a computer program stored thereon, wherein the computer program, when executed by a processor, implements the knowledge graph-based code generation method described above.
[0164] The present invention also provides a computer program product, including a computer program that, when executed by a processor, implements the knowledge graph-based code generation method described above.
Claims
1. A code review method based on multi-agent cooperation, characterized in that, Includes the following steps: Retrieve and preprocess the new code awaiting review; The quantitative risk model identifies risk points in newly added code, forming a structured risk profile for each risk point. The quantitative risk model is built on four dimensions: code value, code style, code quality, and code compliance. By coupling and calculating the risk representations of each dimension, the comprehensive risk score and level of each risk point are determined. The risk profile includes at least the risk location, risk type, risk source, sub-scores for each dimension, and risk level; Based on the structured risk profile, the review rules and historical cases corresponding to the current risk point are retrieved from the comprehensive rule knowledge base according to risk type, contextual semantic relationship and historical handling relationship, and an evidence set corresponding to each risk point is generated. Construct a multi-agent review group, which includes at least two agents. Each agent is configured to simulate different review roles and has a decision function trained based on role knowledge. Based on the risk type, risk level and impact scope in the risk profile, the review role most relevant to the current risk point is adaptively activated. The retrieved evidence set, new code and risk profile are input into each agent, driving each agent to conduct independent analysis based on its role knowledge, evidence citation relationship and decision function, and output review opinions, reasons and confidence level for the risk point. Based on the output of each agent, a comprehensive decision is made. The debate mechanism is initiated only for risk points where the comprehensive risk score is higher than the preset high-risk threshold and there are conflicting opinions. The relevant agents exchange evidence and explain their reasons around the same risk point and dynamically adjust their confidence levels. When the preset consensus conditions are met or the arbitration rules are triggered, the final review conclusion of the risk point is generated and targeted countermeasures are output accordingly.
2. The method of claim 1, wherein, For each risk point its combined risk score The calculation formula is as follows: in, The code value sub-score assesses whether the code achieves core business value or whether there is over-design, under-design, or unnecessary complexity. It indicates code style and assesses whether it conforms to coding standards; Indicates code quality and evaluates internal code quality metrics; The compliance sub-scores assess the code's compliance risks in areas such as security constraints, open-source license compatibility, sensitive API call constraints, and dependency usage standards; each sub-score is normalized to [value missing]. Interval, weighting coefficient Dynamically configured based on project stage, code module type, and risk appetite.
3. The method of claim 2, wherein, any risk point In dimensions Sub-ratings Defined as: in, Indicates the rule matching strength, reflecting the degree to which the code snippet matches the preset rule pattern under this dimension; It represents the static structural anomaly degree, reflecting the degree of structural anomalies extracted based on abstract syntax trees, control flow graphs, and data flow graphs; This indicates the dynamic verification risk level, reflecting the strength of support for the risk point from lightweight execution, symbolic execution, or instrumentation observations. , , These are the weighting coefficients. .
4. The method of claim 1, wherein, The review panel includes business analyst agents and technical lead agents, with the business analyst agent's internal evaluation criteria vector. The following results were obtained by integrating business role preferences, business text knowledge, code structure impact, and risk quantification: in, The semantic feature vector of the business text is obtained by encoding the text of the requirements document, user story and business rule by a pre-trained text encoding model. The feature vector representing the mapping between code and business process is obtained by encoding the code call graph, the scope of influence of interfaces, and the mapping relationship between process nodes. The quantitative risk feature vector representing the risk point is derived from the sub-score in the structured risk profile. This represents vector concatenation. Represents the normalization operator; and The parameter matrix and bias terms representing the role of a business analyst; Internal evaluation criterion vector of technical director agent Constructed by technical director role template, historical technical review samples, and current risk point related features: in, As a technical text feature, The structural analysis features are obtained by extracting code snippets, design specifications, performance results, and review conclusion sample codes from historical review data. and These are the character parameters obtained during training.
5. The method of claim 1, wherein, Let j represent the role of the intelligent agent, and each intelligent agent... Call its decision function to the risk point Perform the calculation: in, Represents intelligent agents Risk points The opinion bias value is used to generate review comments. Indicate risk points The corresponding number Characteristic representation of evidence; It is an intelligent agent Internally stored vector of evaluation criteria related to its role; Represents intelligent agents For the first Weight parameters of class evidence, The bias parameters represent the agent's bias parameters; This indicates the calculation of cosine similarity; The function is the Sigmoid function; K is the total number of pieces of evidence. When Generate a pass opinion if the score is above a preset threshold, otherwise generate a fail opinion; output the corresponding initial confidence score simultaneously .
6. The method of claim 1, wherein, In the debate mechanism, the adjustment of the agent's confidence follows the following iterative formula: in, For intelligent agents Targeting risk points Confidence level after round t of debate For the other party's intelligent agent The strength of the evidence provided As the impact factor, This is the bifurcation damping coefficient. For intelligent agents Targeting risk points The confidence level after round t-1 of debate; the debate mechanism undergoes multiple rounds of iteration, and the debate terminates when the number of iterations reaches a preset maximum value or the consensus level exceeds a preset consensus threshold.
7. The method of claim 1, wherein, The method also includes: extracting code features, risk patterns, and remediation strategies through model mining of historical code, fault records, and repair records, and determining whether to update the comprehensive rule knowledge base with new knowledge newK based on the gain model. in, The gain of new knowledge newK The frequency of occurrence of new knowledge newK The fault impact of new knowledge newK The pattern complexity is newK for new knowledge. This is the smoothing coefficient.
8. The method of claim 2, wherein, Weighting coefficients in quantitative risk models , , , The meta-learning model dynamically generates the weight coefficients based on the project context. The meta-learning model takes at least one of the following as input features: project type, development stage, code module level, and quality gate pass status, and outputs the configured values of the weight coefficients. The meta-learning model is continuously updated online by collecting feedback on the effects of running reviews under different weight configurations as training data. 9.A code review system based on multi-agent cooperation, characterized in that, include: The code input and preprocessing module is used to acquire and preprocess new code to be reviewed; The risk identification and quantification engine is used to identify risk points in newly added code based on a quantitative risk model, forming a structured risk profile for each risk point. The quantitative risk model is built on four dimensions: code value, code style, code quality, and code compliance. By coupling and calculating the risk representations of each dimension, the comprehensive risk score and level of each risk point are determined. The risk profile includes at least the risk location, risk type, risk source, sub-scores of each dimension, and risk level. The comprehensive rule knowledge base is a joint knowledge graph composed of multiple sub-bases, used to generate a searchable, computable, and traceable set of evidence around risk points. The sub-bases include a code rule knowledge base, a historical fault database, a code feature database, and a historical repair database. The multi-agent review group is managed by the agent group management module, which is responsible for lifecycle management, context isolation and role activation control. The review group includes at least two agents, each agent is configured to simulate different review role perspectives and has a decision function trained based on role knowledge. The review-driven and coordination module receives the risk point list output by the risk identification and quantification engine, retrieves the most relevant evidence from the comprehensive rule knowledge base, and adaptively activates the review role most relevant to the current risk point based on the risk type, risk level, and impact scope in the risk profile. It inputs the retrieved evidence set, new code, and risk profile into each agent, driving each agent to conduct independent analysis based on its own role knowledge, evidence citation relationships, and decision functions, and outputs review opinions, reasons, and confidence levels for the risk points. The decision synthesis module is used to make comprehensive decisions based on the outputs of each agent. It initiates a debate mechanism only for risk points where the comprehensive risk score is higher than the preset high-risk threshold and there are conflicting opinions. The relevant agents exchange evidence and explain their reasons around the same risk point and dynamically adjust their confidence levels. When the preset consensus conditions are met or the arbitration rules are triggered, the final review conclusion of the risk point is generated and targeted countermeasures are output accordingly.
10. An electronic device, characterized in that, include: processor; Memory; And a computer program, which is stored in the memory and configured to be executed by the processor, wherein the computer program, when executed by the processor, implements the code review method based on multi-agent collaboration as described in any one of claims 1-8.
11. A computer readable storage medium having stored thereon a computer program, characterized in that, When the computer program is executed by the processor, it implements the code review method based on multi-agent collaboration as described in any one of claims 1-8.
12. A computer program product comprising a computer program, characterized in that, When the computer program is executed by the processor, it implements the code review method based on multi-agent collaboration as described in any one of claims 1-8.