Intelligent code review method and system based on large language model

CN122884516APending Publication Date: 2026-10-09KYLIN CORP
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611078971.7
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-20
Publication Date
2026-10-09

AI Technical Summary

Technical Problem

优点是能够在一定程度上缓解单次输入长度限制并实现跨文件整合纠偏;缺点是提示词内容依赖静态模板与预置知识库填充,缺乏对历史审查经验的动态检索复用,且无法根据变更场景自适应调整权重,亦不具备多源上下文冲突的智能仲裁能力

Benefits of technology

本发明解决了传统代码审查方法中存在的上下文感知不足、历史经验难以复用、提示词设计僵化以及模型调度不稳定等问题。具体而言:

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122884516A_ABST
    Figure CN122884516A_ABST
Patent Text Reader

Abstract

The application discloses an intelligent code review method and system based on a large language model, and the method comprises the following steps: intelligently dividing a code change AST and searching for similar historical review records, symbol definitions and bidirectional call chain information, adjusting weights according to scenes to build context data packages; estimating Token demand and selecting a large language model instance, and performing Token budget allocation according to the window limit and weight of the large language model instance; performing conflict arbitration based on historical review records and call chain information, combining budget allocation and arbitration results to generate optimized prompt words; inputting the large language model to perform review and generate a report. Through the cooperation of dynamic construction of context data packages, Token budget physical isolation and conflict arbitration, the application realizes the precision and intelligence of code review.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to code review technology, specifically to an intelligent code review method and system based on a large language model. Background Technology

[0002] Code review is a core practice for ensuring code quality in software development. It refers to the systematic review of code changes by developers, aiming to promote knowledge sharing within the team. Research shows that effective code review can uncover potential defects, improve code maintainability, significantly reduce defect rates, enhance code consistency, and accelerate the technical integration of new team members. Large language models, with their powerful semantic understanding and code generation capabilities, can automate the analysis of code changes, identify potential problems, and provide improvement suggestions, bringing new possibilities for improving the efficiency and quality of code reviews.

[0003] Currently, code review techniques based on large language models mainly employ the following methods: The method based on simple context concatenation combines code change fragments with a fixed template and submits them directly to the large language model. Its advantage is its simplicity; its disadvantage is the lack of effective utilization of contextual information such as historical review records and code call relationships, resulting in less comprehensive and accurate review results.

[0004] The fixed-keyword approach uses a pre-set static keyword template that is not adjusted based on code characteristics. Its advantage is template reusability; its disadvantage is the inability to dynamically adjust review focus and token allocation according to changing scenarios, leading to the squeezing out of critical information.

[0005] The single-model-based approach involves directly calling a specific large language model service for review. Its advantages are simple integration; its disadvantages include a lack of model fault tolerance mechanisms, resulting in the review process being interrupted when the service is unstable, and the inability to select the optimal model based on the scenario.

[0006] The two-stage template-based approach involves first using a basic review prompt template for initial code review, and then combining this with an expert review prompt template filled with knowledge base information for expert review. The advantages are that it can alleviate the limitation of single input length to some extent and achieve cross-file integration and correction. The disadvantages are that the prompt content relies on static templates and a pre-built knowledge base, lacks dynamic retrieval and reuse of historical review experience, cannot adaptively adjust weights according to changing scenarios, and lacks intelligent arbitration capabilities for multi-source contextual conflicts. Summary of the Invention

[0007] The technical problem to be solved by this invention: 1) Submitting code change fragments directly to the large language model lacks an effective retrieval and integration mechanism for contextual information such as code call relationships and historical review records, and also fails to intelligently identify and arbitrate potential conflicts between historical review suggestions and the facts of the code call chain.

[0008] 2) Existing methods mostly use preset static prompt word templates, which cannot dynamically adjust the prompt word content according to the specific characteristics of code changes, nor can they adaptively adjust the context weight ratio according to different review scenarios such as bug fixes, new features, and refactoring optimizations, resulting in key information being squeezed out and insufficient review targeting.

[0009] 3) Although some improvement solutions introduce a certain degree of domain knowledge through pre-built knowledge bases and template filling, their context sources are still limited to the formatted filling of static knowledge bases and patch metadata, lacking dynamic retrieval and reuse of historical review experience, and are essentially still within the scope of static templates.

[0010] 4) Directly calling a single large language model service lacks unified management of multiple model services, as well as the ability to adaptively switch and degrade when a model fails.

[0011] To address the aforementioned problems in existing technologies, this paper provides an intelligent code review method and system based on a large language model. Through the synergy of four core technologies—AST intelligent segmentation and semantic-symbolic two-dimensional matching, scene-adaptive weight calculation, dynamic prompt word construction, and heterogeneous model scheduling—it achieves intelligent, efficient, and accurate review of code changes, effectively solving core technical challenges in existing technologies such as insufficient context awareness, rigid prompt word design, and unstable model scheduling.

[0012] To solve the above-mentioned technical problems, the technical solution adopted by the present invention is as follows: An intelligent code review method based on a large language model includes the following steps: Receive and parse code change events, and add the parsed events to the task queue as review tasks; After retrieving review tasks from the task queue, the code change content is extracted from them. The code change content is then intelligently segmented into different code blocks using AST. The database is used to match the similar historical review records, symbol definitions, and bidirectional call chain information of each code block. The context information weight is dynamically adjusted according to the current review scenario. The code block data, along with the corresponding similar historical review records, symbol definitions, bidirectional call chain information, context information weight, and the scenario type label of the current review scenario, constitute a context data packet. Based on the estimated token demand and the scenario type labels in the context data package, a large language model is selected. Token budget allocation is performed based on the context window limit of the selected large language model and the context information weights in the context data package. Conflict arbitration is performed based on the similar historical review records and bidirectional call chain information in the context data package. Based on the token budget allocation results and conflict arbitration results, the code block data in the context data package, along with the corresponding similar historical review records and symbol definitions, are used to generate optimized prompt words. The optimized prompt words are then input into the large language model for code quality review. After obtaining the review results, a structured review report is generated. Historical review records, symbol definitions, and call chain information from the review reports are added to the database to form an experience loop.

[0013] Furthermore, the code block is the smallest indivisible syntactic unit. After performing AST intelligent segmentation on the code change content to obtain different code blocks, the method further includes: extracting a local symbol table from each syntactic unit to obtain the corresponding set of defined symbols and set of reference symbols, and injecting four-dimensional metadata into each code block. The four-dimensional metadata includes file path, syntax type, start and end line numbers, and change flag. When matching similar historical review records, symbol definitions, and bidirectional call chain information for each code block in the database, the specific steps include: Using the symbol set as the structured query key, dual-path heterogeneous data retrieval is performed; The system iterates through all historical review records in the database, calculates the cosine similarity between the historical review record and the text of the code block, calculates the symbol similarity between the historical review record and the set of symbols defined in the code block, and calculates the file path matching degree between the historical review record and the code block. Based on the cosine similarity, symbol similarity and file path matching degree, the system calculates the comprehensive similarity and selects historical review records with a comprehensive similarity greater than a preset threshold as similar historical review records of the code block. Another approach involves matching the set of reference symbols of the code block in the database to obtain the complete definition code of the reference symbols as the symbol definition. Then, taking the current modified function to which the code block belongs as the center, the call relationship table is matched at a specified depth to obtain the upstream and downstream call chains of the current modified function.

[0014] Furthermore, the mathematical expression for the overall similarity is as follows:

[0015] in, Sim sem For cosine similarity, Sim sym For symbol similarity, C pathThe file path matching score is calculated by comparing the current code block with the file paths in the historical review records, starting from the root directory of the file path. The score is the number of consecutive matching levels divided by the total number of file paths in the current code block. k is the path enhancement index, which defaults to 1. path When k > 0.8, k = 2; γ(t) is the time decay factor, γ(t) = Δt is the number of days since the historical record was written, and λ is the decay coefficient.

[0016] Furthermore, the context information includes the code block weight W. file Historical record weight W history With symbolic definition of weight W call When dynamically adjusting the weight of contextual information according to the current review scenario, the specific adjustments include: If the current review scenario is a bug fixing scenario, the formula for adjusting the weight of context information is as follows: W history =1.4 W hist_base / Z W call =0.8 W sym_base / Z W file =0.6 W chunk_base / Z If the current review scenario is a new feature scenario, the formula for adjusting the weight of contextual information is as follows: W call =1.6 W sym_base / Z W history =0.6 W hist_base / Z W file =0.6 W chunk_base / Z If the current review scenario is a reconstruction and optimization scenario, the formula for adjusting the weight of context information is as follows: W call =1.4 W sym_base / Z W file =1.2 W chunk_base / Z W history =0.6 W hist_base / Z In the above formula, Z is the normalization factor. Z= W chunk_base + W hist_base + W sym_base W chunk_base The basic weight of the code block is calculated based on the code block's syntax type, the percentage of lines changed, and the importance of symbols; W hist_base The historical record base weight is the result of multiplying the overall similarity of code blocks by the human feedback factor; W sym_base Define a base weight for the symbol. The base weight for the symbol is calculated by combining the current change function call depth, critical path markers, and dependency breadth of the code block.

[0017] Furthermore, when selecting a large language model based on the estimated token demand and the scene type labels in the context data package, the specific steps include: Match scene type labels with a pre-defined scene-model matching rule library to filter out a set of candidate model categories; Within the candidate model category set, priority scores for each instance are calculated using a weighted round-robin algorithm based on real-time load, historical success rate, and cost coefficient. The instance with the highest score is selected. If the large language model context window limit of the selected instance is less than the token requirement, the model category of the selected instance is upgraded and the corresponding instance in the candidate model category set is replaced. In the candidate model category set, the step of calculating the priority score of each instance based on real-time load, historical success rate and cost coefficient through a weighted round-robin algorithm is re-executed to reselect the instance.

[0018] Furthermore, when performing token budget allocation based on the context window limit of the selected large language model and the context information weights in the context data packet, the specific steps include: Obtain the selected large language model context window limit as the total token budget; Based on the code block weight, history weight, and symbol definition weight in the context information weights, Softmax normalization is performed to physically isolate the total token budget into mutually exclusive history budget area, symbol definition budget area, and code block budget area.

[0019] Furthermore, when arbitrating conflicts based on similar historical review records and bidirectional call chain information in the context data packet, the specific steps include: The historical review suggestions with similar historical review records are combined with the call chain structure facts of bidirectional call chain information to form an evidence pair. The large language model is used to extract the operation instructions and their objects in the historical review suggestions, and the dependency state of the objects in the call chain structure facts is extracted. The operation instructions and the dependency state are compared to detect whether there is a conflict. If a conflict is detected, the large language model is invoked to calculate the comprehensive score of the historical review suggestion and the call chain structure facts based on the preset adjudication factors. The arbitration conclusion is determined based on the comparison of the comprehensive scores. The preset adjudication factors include scenario type label, historical credibility, structural constraints, and risk level.

[0020] Furthermore, based on the token budget allocation results and conflict arbitration results, when generating optimized prompts by comparing the code block data in the context data package with the corresponding similar historical review records and symbol definitions, the specific steps include: Based on the token budget allocation results, the allocation budgets for the historical record budget area, the symbol definition budget area, and the code block budget area are determined. Estimate the number of tokens required for each of the similar historical review records, the symbol definitions and bidirectional call chain information, and the code block data, and compare the number of tokens required with the allocation budget of the corresponding segment; If the number of tokens used does not exceed the allocation budget of the corresponding segment, the corresponding content will remain intact; if it exceeds the allocation budget of the corresponding segment, the large language model will be invoked to perform semantic compression on the corresponding content, reducing the original content to within the allocation budget of the corresponding segment while retaining the key information required for review. The processed similar history review records are placed in the history budget area, the processed symbol definitions and bidirectional call chain information are placed in the symbol definition budget area, a scenario-based system instruction is generated according to the scenario type label, an arbitration constraint instruction is generated according to the conflict arbitration result, the scenario-based system instruction and the arbitration constraint instruction are injected into the prompt words, and the optimized prompt words are generated.

[0021] Furthermore, when inputting the optimized prompt words into a large language model for code quality review, the following steps are taken: If a connection timeout, first token timeout, or total generation timeout is triggered, the current large language model instance is abnormal, and it will switch to a backup large language model of the same category to ensure that the session state is not lost. If all alternative large language models in the same category are unavailable, switch to alternative large language models in different categories to ensure that the review process is not interrupted. When the token demand exceeds the context window of the backup large language model, the review content is split into semantically coherent and overlapping sub-fragments based on the AST boundary, and submitted simultaneously to different instances of the backup large language model or different backup large language models through parallel channels for code quality review. The system receives the review results of sub-segments, detects overlapping review comments between sub-segments and removes duplicate suggestions, and combines conflicting comments based on confidence level to form a unified review report.

[0022] This invention also proposes an intelligent code review system based on a large language model, including... The multi-platform access module is used to receive and parse code change events, and add the parsed events as review tasks to the task queue. The code parsing and context building module is used to extract code change content from the task queue after obtaining the review task, perform AST intelligent block division on the code change content to obtain different code blocks, match the similar historical review records, symbol definitions and bidirectional call chain information of each code block in the database, dynamically adjust the context information weight according to the current review scenario, and construct a context data packet by combining the code block data with the corresponding similar historical review records, symbol definitions, bidirectional call chain information, context information weight and the scenario type label of the current review scenario. The large language model integration module is used to select a large language model based on the estimated token demand and the scene type label in the context data package. It performs token budget allocation based on the context window limit of the selected large language model and the context information weight in the context data package. It performs conflict arbitration based on the similar historical review records and bidirectional call chain information in the context data package. Based on the token budget allocation result and the conflict arbitration result, it generates optimized prompt words by combining the code block data in the context data package with the corresponding similar historical review records and symbol definitions. The optimized prompt words are then input into the large language model for code quality review. After obtaining the review results, a structured review report is generated. The data storage module is used to add historical review records, symbol definitions, and call chain information from the review report to the database, forming an experience loop.

[0023] Compared with the prior art, the advantages of the present invention are as follows: This invention addresses the problems of insufficient context awareness, difficulty in reusing historical experience, rigid prompt word design, and unstable model scheduling in traditional code review methods. Specifically: To address the shortcomings of existing technologies that simply submit code change fragments directly to a large language model, lacking an effective retrieval and integration mechanism for contextual information such as code call relationships and historical review records, and failing to intelligently identify and arbitrate potential conflicts between historical review suggestions and the actual code call chain, this invention intelligently segments the code change content using an Abstract Syntax Tree (AST). It then matches similar historical review records, symbol definitions, and bidirectional call chain information in a database. The contextual information weights are dynamically adjusted according to the current review scenario to form a contextual data package. Conflict arbitration is then performed based on similar historical review records and bidirectional call chain information. This achieves a precise association between historical review records and code structure, effectively eliminating false similarity matches and enabling intelligent identification and arbitration of potential conflicts between historical review suggestions and the actual code structure. This significantly improves the comprehensiveness and accuracy of code review and avoids the contamination of current review results by historical false positives.

[0024] To address the issues that existing methods often rely on pre-set static prompt templates, which cannot dynamically adjust prompt content based on specific code changes or adaptively adjust context weighting according to different review scenarios, leading to the overcrowding of key information and insufficient review targeting, this invention estimates token demand based on context data packets, selects a large language model instance based on scenario type tags and token demand, and determines context window limits. Then, it performs token budget allocation based on context window limits and context information weights, and generates optimized prompts by combining conflict arbitration results. This achieves physical isolation and exclusive allocation of token budgets under context window constraints, ensuring that key context information is not overcrowded, significantly improving the targeting of review prompts and the intelligence level of review decisions.

[0025] To address the problem that existing solutions still limit the source of context to static knowledge bases and formatted filling of patch metadata, lacking dynamic retrieval and reuse of historical review experience, and essentially still within the scope of static templates, this invention uses AST intelligent segmentation to match similar historical review records, symbol definitions, and bidirectional call chain information in the database to form a context data package. This enables dynamic retrieval and reuse of historical review experience, breaks through the limitations of static templates, and allows review prompts to adaptively adjust with code change features.

[0026] To address the issues of directly calling a single large language model service, lack of unified management of multiple model services, and the lack of adaptive switching and degradation capabilities in the event of model failure, this invention selects a large language model instance based on scenario type tags and token requirements. This enables the automatic selection of the optimal model according to the review scenario and achieves seamless switching and circuit breaker degradation in the event of model failure, ensuring the high availability and continuity of the review service and significantly improving the robustness and resource utilization efficiency of the system. Attached Figure Description

[0027] Figure 1 This is a schematic diagram of the architecture of an intelligent code review system based on a large language model.

[0028] Figure 2 This is a flowchart of an intelligent code review system based on a large language model.

[0029] Figure 3 This is a flowchart of the workflow of an intelligent code review system based on a large language model. Detailed Implementation

[0030] The present invention will be further described below with reference to the accompanying drawings and specific preferred embodiments, but this does not limit the scope of protection of the present invention.

[0031] Code review is a core component of ensuring software quality. Traditional manual review suffers from inefficiency, strong subjectivity, and difficulty in scaling. In recent years, large language model technology has brought new possibilities for automated code review, but existing solutions still face challenges in areas such as context awareness, prompt word design, and model scheduling.

[0032] Therefore, this embodiment designs an intelligent code review system based on a large language model. For example... Figure 1 As shown, this solution addresses various technical challenges in the code review process by closely coordinating the multi-platform access module, code parsing and context building module, large language model integration module, and data storage module, achieving intelligent, efficient, and accurate review of code changes. The solution aims to automatically link and execute various modules when handling multi-platform access, context building, and model integration, ultimately achieving transparent and efficient intelligent review for users, ensuring high-quality review results and system stability. The working principle is as follows: The multi-platform access module receives code change events through a unified Webhook interface; the code parsing and context building module performs AST intelligent segmentation on code changes, combines semantic-symbolic two-dimensional matching to retrieve similar historical records and call chain information, and dynamically adjusts context weights according to scenario characteristics; the large language model integration module performs token budget allocation and conflict arbitration through a dynamic prompt word builder, and realizes scenario-based scheduling and fault tolerance of heterogeneous models through an LLM gateway; the data storage module adopts a hybrid storage architecture to persist metadata, historical records and review results, forming an experience closed loop.

[0033] Specifically, such as Figure 1As shown, the intelligent code review system based on a large language model comprises four modules: a unified multi-platform access module, a code parsing and context construction module, a large language model integration module, and a data storage module. The code parsing and context construction module includes two sub-modules: diff parsing and intelligent AST segmentation, and enhanced context construction. The large language model integration module includes two sub-modules: a dynamic prompt word builder and an LLM gateway.

[0034] like Figure 2 As shown, in this embodiment, the intelligent code review system based on a large language model forms a complete review loop through the collaborative operation of a multi-platform access module, a code parsing and context construction module, a large language model integration module, and a data storage module. The workflow is as follows: The API gateway in the multi-platform access module receives code change events from platforms such as Gerrit through a unified Webhook interface, performs unified parsing and distribution, and encapsulates the parsed events into review tasks and submits them to the asynchronous task queue. The AST intelligent segmentation module in the code parsing and context construction module extracts code change content from the task queue, uses Tree-sitter for syntax boundary-aware segmentation, extracts the modified code blocks, and establishes four-dimensional metadata. The enhanced context construction module queries the vector database for similar historical review records based on a semantic-symbolic two-dimensional similarity matching algorithm, queries the relational database for complete symbol definitions and bidirectional call chain information, performs multi-factor dynamic weight calculation based on scene characteristics to construct enhanced context fragments, and passes them to the large language model integration module. The dynamic prompt word builder module in the large language model integration module combines the enhanced code context with scene weights, performs token budget allocation and intelligent conflict arbitration to generate optimized prompt words, and then passes them to the LLM gateway. The LLM gateway module selects available model services based on scene tags and token requirements, realizes heterogeneous model scene-based scheduling and adaptive fault tolerance, calls the large language model for code quality review, generates a structured review report after obtaining the review results, and returns it to the corresponding platform. The data storage module stores symbolic metadata and call chains in a relational database (metadata), vectorizes historical review records and stores them in a vector database, and stores the detailed process of review tasks in a relational database (review results), forming an experience closed loop.

[0035] This embodiment also proposes an intelligent code review method based on a large language model. Through the synergy of four core technologies—AST intelligent segmentation and semantic-symbolic two-dimensional matching, scene-adaptive weight calculation, dynamic prompt word construction, and heterogeneous model scheduling—it achieves intelligent, efficient, and accurate review of code changes, effectively solving core technical challenges in existing technologies such as insufficient context awareness, rigid prompt word design, and unstable model scheduling. This method involves the review process executed by the aforementioned review system, such as... Figure 3As shown, the specific process steps are as follows: Step 301: The multi-platform access module receives and parses code change events, adding the parsed events to the task queue as review tasks. The main function of the multi-platform access module is to receive code change events from platforms such as Gerrit, perform unified parsing and distribution, and the specific implementation steps are as follows: 1) The API gateway module provides a unified gateway interface, receives code change information, and eliminates differences in events across different platforms: 1.1) Listen for Webhook events on platforms such as Gerrit, including code commits, merge requests, and code pushes. Use a unified API server as the entry point for Webhook events on all platforms to ensure the reliability of event reception. 1.2) Based on the Webhook format of different platforms, parse the event content and extract key information, such as project name, committer, code changes, file list, etc. 1.3) Encapsulate the parsed events into review tasks and submit them to an asynchronous queue to avoid service timeouts caused by immediate processing.

[0036] 2) Asynchronous task queue module: Review task persistence, save all code change tasks to be reviewed, distribute them as needed, and retain core task information when task processing fails.

[0037] Step 302: The code parsing and context building module retrieves review tasks from the task queue and extracts the code change content. It performs AST intelligent segmentation on the code change content to obtain different code blocks. It matches the database to obtain similar historical review records, symbol definitions, and bidirectional call chain information for each code block. It dynamically adjusts the context information weight according to the current review scenario and constructs a context data packet by combining the code block data with the corresponding similar historical review records, symbol definitions, bidirectional call chain information, context information weight, and scenario type label of the current review scenario.

[0038] The code parsing and context building module constructs an enhanced context data package containing code semantics, historical experience, and structural facts through syntactic parsing of code changes and retrieval of multi-source heterogeneous data. It also evaluates the value weight of various data types relative to specific review scenarios, providing weighted raw data support for subsequent large language model integration. The specific implementation steps are as follows: 1) The diff parsing and AST intelligent segmentation module utilizes the Tree-sitter parser to perform syntax boundary-aware segmentation of code changes: In this embodiment, a code block is the smallest indivisible syntactic unit. After performing AST intelligent segmentation on the code change content to obtain different code blocks, a local symbol table is extracted from each syntactic unit to obtain the corresponding set of defined symbols and set of referenced symbols. Four-dimensional metadata is injected into each code block. The four-dimensional metadata includes file path, syntax type, start and end line numbers, and change flag.

[0039] Specifically, the diff parsing and AST intelligent segmentation module identifies the smallest indivisible syntactic units (function definitions, class definitions, conditional statement blocks, loop bodies, etc.) and establishes syntactic boundary markers; it extracts local symbol tables (definition symbols and reference symbols) from each syntactic unit and establishes a code block-symbol inverted index; it injects four-dimensional metadata (file path, syntax type, start and end line numbers, change markers) into each code block and establishes a bidirectional mapping table between the original code and the segmented content to support precise line-level positioning of subsequent review results.

[0040] 2) The enhanced context building module includes a dual-path fusion retrieval mechanism, a semantic-symbolic two-dimensional similarity matching algorithm, and a scene-adaptive multi-factor dynamic weight calculation model, which enables accurate retrieval and dynamic fusion of historical experience, call chain relationships, and file context.

[0041] In this embodiment, when the database is used to match similar historical review records, symbol definitions, and bidirectional call chain information for each code block, the enhanced context building module specifically performs the following steps: 2.1) Dual-path fusion retrieval: Based on the symbol set extracted by AST intelligent block segmentation as the structured query key, dual-path heterogeneous data retrieval is performed. ① Vector retrieval path: Traverse all historical review records in the database, calculate the cosine similarity between the traversed historical review record and the text of the code block, calculate the symbol similarity between the traversed historical review record and the definition symbol set of the code block, and calculate the file path matching degree between the traversed historical review record and the code block. Calculate the comprehensive similarity based on cosine similarity, symbol similarity, and file path matching degree, and select historical review records with a comprehensive similarity greater than a preset threshold as similar historical review records for the code block. Specifically, the code block generated by the diff parsing and AST intelligent segmentation module in step 1) is encoded into a vector. V query A semantic-symbolic two-dimensional similarity matching algorithm is used to traverse all historical review records in the vector database to retrieve similar historical review records, where: In the semantic dimension, a code-specific embedding model (such as CodeBERT) is used to calculate the cosine similarity between the traversed historical review records and the text of the code blocks. Sim sem Capture the similarity of code logic structure; For the symbol dimension, based on the symbol set (function name, class name) extracted by the diff parsing and AST intelligent block segmentation module in step 1), the symbol similarity between the traversed historical review records and the definition symbol set of the code block is calculated. Sim sym (Using Jaccard coefficients: |Symbols) cur ∩Symbols hist | / |Symbols cur ∪Symbols hist |), ensuring the consistency of business objects; A two-dimensional weighted synthesis is used to calculate the file path matching degree between the traversed historical review records and the code blocks.

[0042] in, Sim sem For cosine similarity, Sim sym For symbol similarity, C path The file path matching degree is given by k, which is the path enhancement exponent. The default value of k is 1. When C path When k > 0.8, k = 2; γ(t) is the time decay factor, γ(t) = Δt is the number of days since the historical record was written, and λ is the decay coefficient (default 0.01).

[0043] The file path matching degree is calculated based on the file path in the four-dimensional metadata from step 1): Specifically, starting from the root directory of the file path, the current code block is compared layer by layer with the file paths corresponding to the historical review records. The number of consecutive matching levels is recorded, and then divided by the total number of levels of the current code block's file path to obtain the path matching degree. C path Taking the path src / core / moduleA / file1.c as an example, its total hierarchy is 4 levels (src, core, moduleA, file1.c): If the historical records correspond to the same file src / core / moduleA / file1.c, and the number of consecutive matching levels is 4, then C path =4 / 4=1.0 If the historical records correspond to different files under the same module, such as src / core / moduleA / file2.c, and the consecutive matching level is 3 (matching up to moduleA, filename does not match), then... C path =3 / 4=0.75 If the historical records correspond to different module files src / display / moduleB / ui.c, and the match stops after reaching src, with a consecutive matching level of 1, then... C path =1 / 4=0.25 when C path When the value is greater than 0.8, it indicates that the current code block and the history block highly overlap from the same file or path. In this case, the path enhancement index k is increased from the default value of 1 to 2. C path Square-order gain C k path Participate in the comprehensive similarity calculation to prioritize recalling historical review experience within the same module / file; when C path When k=1, the path term is not squared.

[0044] The geometric mean term ensures that both semantic and symbolic dimensions must score highly to achieve high similarity; a low score in either dimension will significantly lower the result. The path enhancement term provides non-linear similarity amplification to code within the same module; when C... path A quadratic gain of >0.8 triggers priority recall of historical review experience within the same module; a time decay factor ensures priority reuse of recent review experience; the combined effect of these three factors effectively eliminates pseudo-similar records with "similar code structures but completely different operational objects," resulting in a refined candidate set S'. hist .

[0045] ② Symbol retrieval path: Match the set of reference symbols of the code block in the database to obtain the complete definition code of the reference symbols as the symbol definition. Then, with the current modified function to which the code block belongs as the center, match the call relationship table at a specified depth to obtain the upstream and downstream call chains of the current modified function. Specifically, based on the set of reference symbols (function name, class name, global variable) extracted by the diff parsing and AST intelligent block segmentation module in step 1), perform a precise query in the relational database (metadata) to obtain the complete definition code (function body, class implementation) of these symbols, ensuring that the model understands the specific logic of the callee; based on the call relationship table (Caller, Callee, CallType, LineNum), set the maximum depth D. max =3, construct a bidirectional call chain centered on the current changed function: the upstream call chain (which functions / modules call the current function, used for impact analysis) and the downstream call chain (which key functions the current function depends on, used for dependency risk assessment).

[0046] 2.2) The scenario-adaptive multi-factor dynamic weight calculation model dynamically adjusts the weights of context information according to the current review scenario. It automatically adjusts the weight ratios of the three types of context information based on different review scenarios, improving the accuracy and efficiency of review in specific scenarios. ① Mechanism for obtaining basic weights.

[0047] Code block base weight W chunk_base Based on the diff parsing and AST intelligent segmentation results in step 1), the weight of code block syntax (function definition 1.0, class definition 0.8, ordinary code block 0.5), the proportion of changed lines (higher proportion, higher weight), and symbol importance (whether it contains key functions) are comprehensively calculated. This calculation ensures that core logic units receive the highest token budget allocation through syntax type differentiation, preventing ordinary code snippets from crowding out key function review resources; combined with dynamic weighting based on the proportion of changed lines, large-scale changed code blocks receive higher attention, improving the detection rate of high-risk changes; symbol importance marking further strengthens the contextual priority of key business functions, ensuring that core logic is not overlooked. The formula is as follows: W chunk_base = W type (1+ α R change ) (1+ β I critical ) in, W type Assuming a base weight for syntax types, functions are defined as 1.0, classes as 0.8, and ordinary code blocks as 0.5. R change The percentage of lines modified refers to the proportion of the number of lines modified in the current code block out of the total number of lines in the code block. α The adjustment factor for changing the percentage of rows is set to the default value. α =0.5; I critical This is a symbol importance marker. If the current code block contains a critical function (such as a security-sensitive function or a core interface function), the value is 1; otherwise, the value is 0. β This is an adjustment factor for the importance of the sign, defaulting to... β =0.4. Using the above formula, the core code block of the syntax type receives a higher base weight; the higher the change ratio, the greater the weight. Code blocks containing key symbols receive an even greater weight increase.

[0048] Historical Record Base Weight Whist_base Based on the two-dimensional similarity matching result Sim from step 2.1), total Combined with the manual feedback factor (×1.2 for "valid" and ×0.5 for "false alarm"), the calculation is as follows: As a foundation, records with high similarity are prioritized for reuse; the time decay factor γ(t) ensures that records within 30 days retain more than 75% effective weight, prioritizing the recall of recent high-quality review experience and avoiding obsolescence from outdated records interfering with current judgments; the manual feedback factor enables dynamic screening of experience quality, amplifying the weight of effective records and quickly suppressing false alarm records, significantly improving the accuracy of historical experience reuse and reducing the contamination of review results by false alarm history. The formula is: W hist_base = Sim total γ ( t ) F feedback in γ(t)=e λΔt The time decay factor, Δt This is the number of days since today in historical records. λ This is the attenuation coefficient (default 0.01). F feedback When the manual feedback factor is marked as "valid", F feedback =1.2, when marked as "false alarm" F feedback =0.5, when unmarked F feedback =1.0. Using the above formula, historical records with high similarity receive higher base weights, recent records are preferentially retained due to the time decay factor, valid records receive weight amplification, and false positive records are suppressed.

[0049] Symbolic definition of basic weight W sym_base Based on the query results of the symbol retrieval path, and considering the call depth (1.0 for direct calls, decreasing by 0.2 for each additional layer), critical path marking (security-related ×1.5), and dependency breadth (×1.2 for upstream call count > 5), a comprehensive calculation is performed. This calculation avoids excessively deep call chains crowding out the token budget, ensuring that critical symbols in direct calls receive the highest weight; critical path marking forcibly increases the context priority of sensitive symbols, reducing the risk of missed detections; dependency breadth weighting identifies high-impact symbols, ensuring that widely relied-upon critical functions receive sufficient context support. The formula is as follows: W sym_base =W depth M critical B breadth in W depth =max(1.0 0.2 (d 1), 0.2), where d is the call depth (d=1 for direct calls, and increases by 1 for each additional call depth), and the minimum is not less than 0.2; M critical Mark the critical path; if the symbol involves a security-sensitive operation, then... M critical =1.5, otherwise M critical =1.0; B breadth To depend on the breadth factor, if the number of upstream callers for the current symbol is greater than 5, then... B breadth =1.2, otherwise B breadth =1.0. According to the above formula, symbols that are directly called receive the highest weight, and the weight decreases with increasing call depth. Critical path symbols and widely dependent symbols receive additional weight increases.

[0050] ② Scene recognition and dynamic weight calculation: Construct a scene-adaptive weight calculation model. Automatically identify the current review scene through a rule engine and a lightweight classifier (such as based on file path, change mode, keywords) and apply different weight calculation strategies.

[0051] If the current review scenario is a bug fix scenario (identification features: submission information contains "fix / bug", and modifications are concentrated on conditional judgment / exception handling), the weight coefficient of the history record is automatically increased to 1.4 (reusing similar bug fix experience), and the weight of the file context is decreased to 0.6. The formula for adjusting the weight of the context information is as follows: W history =1.4 W hist_base / Z W call =0.8 W sym_base / Z W file =0.6 W chunk_base / Z Where Z is the normalization factor, calculated using the following formula: Z = Wchunk_base + W hist_base + W sym_base That is, Z is the base weight of the current code block. W chunk_base Historical data base weight W hist_base Basic weights defined by symbols W sym_base The sum of the three. Technical effect: Increased detection rate of similar bugs, avoiding duplicate reviews.

[0052] If the current review scenario is a new feature scenario (identifying features: new files / functions, containing "add / feature"), automatically increase the symbol definition weight coefficient to 1.6 (understanding existing dependencies), decrease the history weight to 0.6, and the file context weight to 0.6. The formula for adjusting the context information weight is as follows: W call =1.6 W sym_base / Z W history =0.6 W hist_base / Z W file =0.6 W chunk_base / Z Technical effects: Improved detection rate of interface compatibility issues, reducing defects caused by incomplete understanding of dependencies.

[0053] If the current review scenario is a refactoring and optimization scenario (identifying features: modifications across multiple files, including "refactor"), automatically increase the symbol definition weight coefficient to 1.4, the file context weight to 1.2 (impact analysis), and decrease the history weight to 0.6. The formula for adjusting the context information weight is as follows: W call =1.4 W sym_base / Z W file =1.2 W chunk_base / Z W history =0.6 W hist_base / Z Technical benefits: Improved cross-file impact recognition coverage and prevention of cascading defects introduced by reconstruction.

[0054] If the current review scenario is a security scenario (identification feature: involving password / permission related symbols), automatically increase the weight of critical path symbols to 2.0, decrease the weight of history records to 0.6, and decrease the weight of file context to 0.4. The formula for adjusting the weight of context information is as follows: W call =2.0 W sym_base / Z W history =0.6 W hist_base / Z W file =0.4 W chunk_base / Z Technical effect: Reduced rate of missed security vulnerability detection.

[0055] The coefficients selected above are based on the constraints of token budget allocation and the principle of maximizing information value: after Softmax normalization, the dominant dimension should account for more than 40% to ensure effective focus of model attention, the auxiliary dimension should account for 20%-30% to retain necessary information, and the compressed dimension should account for less than 20% to release tokens to high-value information. A lower limit of 0.6 for the file dimension can retain the syntax boundary information of changed code blocks (approximately 20-30 lines of AST metadata), ensuring line-level positioning accuracy; a lower limit of 0.4 only retains the definitions of key symbols, suitable for security scenarios where "only key function call relationships are of concern". The upper limit of the dominant dimension coefficient is 2.0 to avoid other dimensions being compressed to below 15% and losing necessary auxiliary information, while the lower limit is 1.4 to ensure that the normalized dimension accounts for more than 40% to form an effective dominant dimension. All coefficients are multiples of 0.2 to facilitate the configuration of the system's discretized storage, and a step size of 0.2 (approximately 10% weight change) represents a significant difference perceptible to humans.

[0056] The weight adjustment strategies for the four scenarios form an orthogonal design, where the directions of change for the three types of context weights are different in each scenario, and the adjustment directions for at least two dimensions are opposite in any two scenarios. Specifically: Bug fixing scenarios: Increase the weight of historical records (×1.4), decrease the weight of symbol definitions (×0.8), decrease the weight of file context (×0.6), and highlight the reference value of similar historical experiences for current bug fixing; New feature scenarios: history record weight reduced (×0.6), symbol definition weight increased (×1.6), file context weight reduced (×0.6), emphasizing understanding of existing interfaces and dependencies to avoid compatibility issues introduced by new features; Refactoring optimization scenario: historical record weight reduced (×0.6), symbol definition weight increased (×1.4), file context weight increased (×1.2), with emphasis on the impact analysis of refactoring on the call chain and consistency checks of cross-file changes; Security scenario: The weight of historical records is reduced (×0.6), the weight of symbol definitions is greatly increased (×2.0), and the weight of file context is greatly reduced (×0.4). The focus is on strict review of sensitive symbols (such as permission verification, encryption and decryption, memory allocation, etc.), and other context information gives way to critical path symbol analysis.

[0057] In the above design, at least two dimensions of any two scenarios have opposite adjustment directions, ensuring that the weight allocation will deviate significantly when a scenario is identified incorrectly, thus allowing the system to detect and verify the error. Taking the Bug Fixing scenario and the New Feature scenario as examples: Bug Fixing is "History ↑, Symbol ↓, File ↓", while New Feature is "History ↓, Symbol ↑, File ↓", with opposite directions of change in the two dimensions; the Bug Fixing scenario and the Refactoring / Optimization scenario are "History ↑, Symbol ↓, File ↓" and "History ↓, Symbol ↑, File ↑", with all three dimensions reversed; the New Feature scenario and the Security scenario are "History ↓, Symbol ↑, File ↓" and "History ↓, Symbol ↑↑, File ↓↓", with amplitude differences in both the symbol and file dimensions. This orthogonal design ensures that the weight configuration between different scenarios has significant distinguishability.

[0058] Finally, a weighted context data packet is output to step 303, containing: scene type label, scene adaptive weight coefficient (W). history W call W file ), AST block code data (with four-dimensional metadata), symbol definition and bidirectional call chain data, and refined historical review record data (with similarity and validity markers).

[0059] Step 303: The large language model integration module selects a large language model based on the estimated token demand and the scene type labels in the context data package. It performs token budget allocation based on the context window limit of the selected large language model and the context information weights in the context data package. It performs conflict arbitration based on the similar historical review records and bidirectional call chain information in the context data package. Based on the token budget allocation results and conflict arbitration results, it generates optimized prompt words by combining the code block data in the context data package with the corresponding similar historical review records and symbol definitions. The optimized prompt words are then input into the large language model for code quality review. After obtaining the review results, a structured review report is generated.

[0060] The large language model integration module receives the weighted context data package output from step 302 and is responsible for all technical decisions related to the large language model, including resource budget allocation based on the LLM context window feature, intelligent arbitration of context conflicts based on LLM inference capabilities, dynamic generation and physical assembly of prompt words, and scheduling and fault tolerance of heterogeneous model services. The specific implementation steps are as follows: 1) The Dynamic Prompt Builder module is used for token budget allocation and dynamic prompt generation.

[0061] When allocating the token budget based on the context window limit of the selected large language model and the context information weights in the context data packet, specifically, it uses the actual selected large language model's context window limit (e.g., T_max=6000 for the GPT-48K version, and T_max=100000 for the 128K version), combined with the scene-adaptive weight coefficients output in step 302 (code block weights, history weights, and symbol definition weights in the context information weights), to perform Softmax normalization. This physically isolates the total token budget into three mutually exclusive segments: T_history (history budget), T_call (symbol definition budget), and T_file (code block budget), ensuring that the budget for each segment is not crowded out. Based on the above budget constraints, this module executes the following dynamic generation process: 1.1) Conflict Detection and Intelligent Arbitration: The historical review suggestions with similar historical review records are combined with the call chain structure facts of bidirectional call chain information to form an evidence pair. The large language model is used to extract the operation instructions and their objects in the historical review suggestions, and the dependency state of the objects in the call chain structure facts is extracted. The operation instructions and the dependency state are compared to detect whether there is a conflict. If a conflict is detected, the large language model is invoked to calculate the comprehensive score of the historical review suggestion and the call chain structure facts based on the preset adjudication factors. The arbitration conclusion is determined based on the comparison of the comprehensive scores. The preset adjudication factors include scenario type label, historical credibility, structural constraints, and risk level.

[0062] Specifically, the historical review suggestions output in step 302 (such as "delete function X") and the call chain structure facts (such as "function X is called by 3 critical paths") are combined into an evidence pair. A lightweight detection prompt is injected, and a large language model is invoked to perform logical tension detection. The prompt first specifies that the model acts as a code review logic verifier, tasked with determining whether there is a logical contradiction between historical review experience and the current code structure facts. Then, the evidence pair is labeled as historical suggestion A and call chain fact B, respectively. The model is required to extract the operation instructions and their objects from historical suggestion A, and simultaneously extract the dependency status of the objects in call chain fact B. Then, the model is compared and judged according to three types of patterns: behavioral conflict, scope conflict, and priority conflict. A behavioral conflict refers to historical suggestion A requiring the deletion or signature change of a function, while call chain fact B indicates that the function still has active upstream or downstream calls. Dependency: Performing this operation will cause the bidirectional call chain constructed in step 302 to break. Scope conflict means that the code object targeted by historical suggestion A is limited to a local scope, while call chain fact B shows that the object actually has cross-module reference attributes, and its scope of influence exceeds the boundary identified by historical suggestion A. Priority conflict means that the processing strategy advocated by historical suggestion A does not match the critical path attributes marked by the code entity in step 302. For example, the suggestion advocates rapid merging, but the facts show that the code entity is in a security verification path. After class-by-class comparison, the model outputs a structured judgment result containing whether a contradiction was detected, the contradiction type, and the reasoning process. For example, if historical suggestion A advocates deleting function X, while call chain fact B shows that function X is called by upstream functions on three critical paths, then the behavior conflict judgment is true.

[0063] If a conflict is detected (the suggestion contradicts the facts), a specialized conflict arbitration prompt fragment is constructed, and a comprehensive scenario label (such as a conservative strategy required in a bug fixing scenario) and historical credibility (Sim) are invoked from a large language model. totalThe system uses contextualized adjudication based on factors such as human feedback and structural constraints (call depth, critical path markers). The prompt first designates the model as an arbitrator for code review conflicts; then, the scenario type label, code block comprehensive similarity (Simtotal), human feedback markers, call depth, and critical path markers output from step 302 are injected as adjudication factors. These factors are then weighted and summed according to preset weights to calculate the combined score of historical suggestion A and call chain fact B. The higher score is adopted; if the difference between the two scores is less than 0.15, a compromise solution is output.The scenario weight factors are assigned values ​​based on the scenario type tags identified in step 302. The weight for bug fixing scenarios is 0.35, for security scenarios 0.40, for new feature scenarios 0.25, and for refactoring and optimization scenarios 0.20. These values ​​are determined based on the sensitivity of each scenario to code stability and correctness. Security scenarios involve permission verification and data protection, and the consequences of misjudgment are the most severe, hence the highest weight. Bug fixing scenarios need to balance the correctness of the fix with the introduction of new risks, so the weight is second highest. New feature and refactoring / optimization scenarios allow for a certain degree of trial and error, so the weights are relatively low. The historical reliability factor has a weight of 0.2. 5. Based on the Simtotal value and the manual feedback markers, the value is set to 1.0 when Simtotal is greater than or equal to 0.8 and the feedback is valid; 0.8 when Simtotal is greater than or equal to 0.6 and the feedback is valid; 0.2 when the feedback is a false alarm; and the Simtotal value is used when there is no feedback. The thresholds of 0.8 and 0.6 are set according to the distribution statistics of comprehensive similarity in step 302. The historical records of Simtotal greater than or equal to 0.8 and the current code block have a high degree of consistency in both semantic and symbolic dimensions. When Simtotal is greater than or equal to 0.6, at least one of the semantic or symbolic dimensions reaches a certain level. A moderate matching level is considered; a score below 0.6 indicates insufficient matching quality to be convincing. The structural constraint factor weight is set to 0.25, calculated based on the call depth and critical path markers in call chain fact B. For direct calls (depth 1), the weight is 1.0, decreasing by 0.2 for each additional depth, with a minimum of 0.2. When the critical path marker is true, it is multiplied by an additional 1.5. This attenuation factor of 0.2 is based on the diminishing marginal utility of call chain information in code understanding. The symbolic definition of direct calls is crucial for understanding the current function logic. As call depth increases, the impact of indirect dependencies on the current review decision gradually weakens, with a minimum value of 0.2. The deep call chain retains a certain reference weight rather than being completely discarded. The critical path amplification factor of 1.5 is set based on the decisive role of security-sensitive paths and core business paths in review decisions. The risk level factor weight is set to 0.15, automatically assigned based on the conflict type output by conflict detection: 0.9 for behavioral conflicts, 0.6 for scope conflicts, and 0.7 for priority conflicts. These values ​​are determined based on the degree to which each type of conflict damages the correctness of the code. Behavioral conflicts directly involve changes to the existence of code entities and have the highest risk; priority conflicts involve inappropriate handling strategies and have the second highest risk; scope conflicts mainly affect the focus of review and have a relatively low risk. The model's final output is a structured arbitration conclusion that includes the ruling result, scores for both parties, reasons for the ruling, and implementation suggestions. This conclusion serves as the input for the dynamic strategy assembly in step 303, used to generate optimized prompt words.

[0064] 1.2) Dynamic strategy assembly: Based on the token budget allocation results and conflict arbitration results, the code block data in the context data package is compared with the corresponding similar historical review records and symbol definitions to generate optimized prompt words. Specifically, based on the scene tags from step 302 and the LLM arbitration conclusion (if any), the process of generating the final prompt words is as follows: ① Based on the Token budget allocation results, the allocation budgets for the historical record budget area, symbol definition budget area, and code block budget area are determined. Specifically, the remaining Token budget is allocated to three mutually exclusive segments, T_history, T_call, and T_file, according to the Softmax normalization result. Each segment's budget is used independently and does not encroach on the others. ② Estimate the token requirements for each of the similar history review records, symbol definitions and bidirectional call chain information, and code block data, and compare the token requirements with the allocation budget for the corresponding segment. Specifically, estimate the token requirements for each of the similar history review records to be placed in the T_history segment, the symbol definitions and bidirectional call chain information in the T_call segment, and the code block data in the T_file segment, and compare the estimation results with the allocation budget for the corresponding segment one by one; ③ If the number of tokens used does not exceed the allocation budget of the corresponding segment, the corresponding content will remain intact; if it exceeds the allocation budget of the corresponding segment, the large language model will be invoked to perform semantic compression on the corresponding content, reducing the original content to within the allocation budget of the corresponding segment while retaining the key information required for review. Specifically, if the estimated number of tokens for the original content of a segment does not exceed the allocation budget of that segment, the content of that segment will remain intact; if it does exceed the budget, the large language model will be invoked to perform semantic compression on the original content of that segment, and the compression instruction will specify that the large language model will reduce the content of that segment to within the target number of tokens while retaining the key information required for review. ④ Place the processed similar history review records in the history budget area, and place the processed symbol definitions and bidirectional call chain information in the symbol definition budget area. Generate scenario-based system instructions based on the scenario type label, generate arbitration constraint instructions based on the conflict arbitration result, and inject the scenario-based system instructions and the arbitration constraint instructions into the prompt words to generate optimized prompt words. Specifically, the content of each segment processed in step ③ is physically arranged according to the budget segment: the T_call segment contains symbol definitions and bidirectional call chain information, the T_history segment contains similar history review records, and the T_file segment contains AST block code data and four-dimensional metadata. The compression judgment and execution of each segment are performed independently and do not affect each other.

[0065] 2) The LLM gateway module serves as an intermediate abstraction layer between the application layer and the large language model service. It encapsulates heterogeneous model services (including but not limited to models from different vendors and architectures such as Qwen, GPT-4, Claude, and Llama) through a unified protocol, builds a multi-active service pool and an intelligent routing decision engine, and achieves accurate matching between model capabilities and review requirements as well as adaptive fault tolerance in case of failure.

[0066] 2.1) Model Service Pooling Management and Hot-Swap Mechanism: Establish a multi-model registry center to maintain a list of available models and their multi-dimensional capability profiles (context window length, specialized languages, cost coefficient, response latency baseline, and domain-specific identifiers). Support hot-swap registration of models: New model instances are dynamically added to the service pool after passing a health check, without requiring a gateway restart; periodic heartbeat detection is used, sending a lightweight ping probe every 30 seconds. If three consecutive pings fail or the response latency exceeds 200% of the baseline, the model is marked as unavailable and automatically removed from the routing table.

[0067] 2.2) Contextualized Two-Level Intelligent Routing Decision: When selecting a large language model based on the estimated token requirement and the contextual type label in the context data packet, the system receives the contextual type label (Bug Fix / New Feature / Refactoring / Security Scenario) output by the prompt word builder and the estimated token requirement, and performs a cascading decision between primary and secondary routes: ① Primary Routing (Scenario-Capability Matching): Matches scenario type tags to a pre-defined scenario-model matching rule library to filter out a set of candidate model categories. Specifically, it is based on a pre-defined scenario-model matching rule library (e.g., security scenarios prioritize matching dedicated models fine-tuned from the CVE corpus, and C++ code prioritizes matching models that support more than 32K contexts), combined with domain-specific identifiers and context window limitations in the capability profile, to filter out a set of candidate model categories; ② Secondary routing (load balancing and cost optimization): Within the candidate model category set, priority scores for each instance are calculated using a weighted round-robin algorithm based on real-time load, historical success rate, and cost coefficient. The instance with the highest score is selected. If the large language model context window limit of the selected instance is less than the token requirement, the model category of the selected instance is upgraded and the corresponding instance in the candidate model category set is replaced. In the candidate model category set, the step of calculating the priority score of each instance based on real-time load, historical success rate and cost coefficient through a weighted round-robin algorithm is re-executed to reselect the instance.

[0068] Specifically, within the candidate categories, a priority score for each instance is calculated using a weighted round-robin algorithm based on real-time load (current concurrent requests), historical success rate (success rate of the most recent 100 requests), and cost coefficient. S core = w1·(1 / load) + w2·success rate + w3·(1 / cost) The weighting coefficients are empirically recommended values: w1∈[0.2,0.4], w2∈[0.4,0.6], w3∈[0.1,0.3], satisfying w2>w1≥w3 and w1+w2+w3=1. In actual deployment, these values ​​can be dynamically adjusted within the above range based on cluster load characteristics, cost budget, and quality requirements. Success rate weighting is recommended as the highest priority, as code review failures will directly lead to the omission of potential defects. If w2 is below 0.4, low success rate instances may be selected, increasing the risk of review failure. If it is above 0.6, excessive compression of load and cost factors may lead to increased response latency for high-load instances or frequent calls to high-cost instances, resulting in budget overruns. Load weighting is recommended as the second priority to avoid excessively high response latency for high-concurrency instances. If w1 is below 0.2, it is not sensitive to load fluctuations, causing requests to wait in the queue for a long time. If it is above 0.4, even slight load fluctuations will trigger instance switching, increasing connection overhead. Cost weighting is recommended as a reference factor, with costs moderately controlled while meeting quality and performance requirements. If w3 is below 0.1, cost hardly participates in the decision-making process, and the most expensive high-performance instance may always be selected. If it is above 0.3, low-quality instances may be selected to save costs. Recommended configuration schemes include quality-first (w1=0.3, w2=0.5, w3=0.2, suitable for core business code review), cost-sensitive (w1=0.25, w2=0.45, w3=0.3, suitable for non-core projects or budget-constrained scenarios), and performance-first (w1=0.4, w2=0.45, w3=0.15, suitable for emergency release scenarios). It is recommended to dynamically optimize the weight values ​​during operation based on monitoring metrics (P99 latency, error rate, average cost per request). The highest-scoring specific instance is selected as the primary model. If the context window limit of all instances in the current candidate model category set is less than the estimated total token requirement, a model category upgrade is triggered (e.g., from a 32K window category to a 128K window category), the candidate model category set is updated, and the secondary routing is re-executed to select the highest-scoring specific instance as the primary model. After selecting an instance, its context window limit is T_max, used to execute the token budget allocation and segment content compression in step ③ of section 1.2).

[0069] In one implementation, the estimation of token requirements includes: using a tokenizer corresponding to the target large language model, encoding the code block data, similar historical review records, symbol definitions, and bidirectional call chain information in the context data packet, and counting the number of tokens corresponding to each part; superimposing the fixed overhead of the prompt word template (including the token usage of contextualized system instructions, arbitration constraint instructions, role settings, and output format constraints) to obtain the estimated total token requirement. This estimated total token requirement is used for the model selection decision of the LLM gateway: if the estimated total token requirement exceeds the upper limit of the context window of the candidate model instance, a model category upgrade is triggered.

[0070] In this embodiment, when the optimized prompt words are input into the large language model for code quality review, the LLM gateway module also performs the following steps: 2.3) Adaptive fault tolerance and circuit breaker degradation: If a connection timeout, first token timeout, or total generation timeout is triggered, the current large language model instance is abnormal, and it will switch to a backup large language model of the same category to ensure that the session state is not lost. If all alternative large language models in the same category are unavailable, switch to alternative large language models in different categories to ensure that the review process is not interrupted. If all alternative large language models in the same category are unavailable, switch to alternative large language models in a different category to ensure that the review process is not interrupted.

[0071] Specifically, tiered timeout thresholds are set: connection timeout (5 seconds, establishing a TCP / TLS connection), first token timeout (10 seconds, returning the first byte), and total generation timeout (dynamically adjusted from 60-180 seconds based on the scale of changes identified by the prompt word builder). Triggering any of these thresholds determines the current model instance is abnormal, immediately and seamlessly switching requests to a backup model of the same category, ensuring session state is not lost. If all models of the same category are unavailable, cross-category degradation is implemented (e.g., downgrading from GPT-4 to a local lightweight Llama instance or a cached rule engine) to ensure uninterrupted review processes. A sliding window counting method (60-second window size) is used to monitor the failure rate. When the failure rate > 50% and the number of requests > 10, the faulty model is automatically circuit-broken, entering a half-open probe state (allowing one probe request every 60 seconds to verify recovery) to prevent cascading failures.

[0072] 2.4) Streaming fragmented review and result aggregation: When the token demand exceeds the context window of the backup large language model or the main model, the review content is split into semantically coherent and overlapping sub-fragments based on the AST boundary, and submitted to different instances of the backup large language model or different backup large language models simultaneously through parallel channels for code quality review. The system receives the review results of sub-segments, detects overlapping review comments between sub-segments and removes duplicate suggestions, and combines conflicting comments based on confidence level to form a unified review report.

[0073] Specifically, when the selected model's context window is insufficient to accommodate all changes and associated contexts for the current review task, the LLM gateway triggers adaptive fragmented review: First, the number of changed files involved in the task and the size of each file are assessed. If the total number of tokens for multiple files exceeds the limit, the files are split at the file level, encapsulating one or more files into a review sub-fragment. If a single file exceeds the limit due to excessive content or associated context, it is divided into several semantically complete sub-fragments based on the AST syntax boundaries according to function definitions and class definitions, ensuring that the number of tokens for each sub-fragment is appropriate for the used model window. Each sub-fragment is submitted simultaneously to different service instances of the same model or different models via parallel asynchronous channels, carrying a unified parent request identifier, and each independently performs code quality review reasoning, generating intermediate review opinions with sub-fragment identifiers. After all sub-segments are returned, the LLM gateway aggregates the results: based on the context overlap boundaries preserved during segmentation, it identifies and removes identical defect opinions that are repeated across segments, retaining only the one with the highest confidence level; for contradictory opinions arising from the same code location in different sub-segments, it weights the votes according to confidence scores, using the one with the highest score as the final conclusion, and attaches explanations of the contradictions and the basis for the decision to the review report. After aggregation, a unified structured review report covering all changed files is generated, pushed to the original code hosting platform via the API gateway, and simultaneously submitted to the data storage module for persistence.

[0074] 2.5) Three-level refined flow control: System-level: Leaky bucket algorithm based on token consumption rate (bucket capacity is 10 times T_max, and the leakage rate is dynamically adjusted according to the model RPM limit) to prevent overall overload; Tenant level: Configure independent quota pools for different projects / teams (e.g., reserve 30% capacity for core projects and share the remaining 70% for ordinary projects), and implement quota isolation through the token bucket algorithm to prevent a single project from exhausting resources; Task level: For extremely large code changes (the number of tokens exceeds the single model window), implement concurrent rate limiting on the basis of streaming sharding (a maximum of 3 shard requests can be submitted at the same time) to avoid sudden traffic surges.

[0075] 3) Structured processing and feedback of review results. The system receives the raw text returned by the large language model and extracts review comments and risk levels through pattern matching and JSON Schema validation. It then uses the four-dimensional metadata output in step 302 to establish a precise bidirectional mapping between review comments and physical line numbers in the source code (solving the line number drift problem caused by segmented review), generating a standardized review report. This report is then pushed in real-time to the original code hosting platform (Gerrit / GitLab / GitHub / Gitea) via the unified API gateway interface in step 301, and inline comments are displayed on the code review interface. Simultaneously, the report object is submitted to step 304 for persistent storage, forming an experience loop.

[0076] Step 304: The data storage module adds the historical review records, symbol definitions, and call chain information from the review report to the database, forming an experience loop.

[0077] The data storage module comprises three databases: a relational database (metadata) for storing all symbol information and call chain relationships of the current project, facilitating the large language model's full understanding of the code structure and the potential impact of the code change; a vector database primarily stores historical review records, enabling quick retrieval of similar review results for the change through similar code snippets, which are then provided to the large language model for reference; and a relational database (review results) for persistent storage of review results, providing visualization of the results and enabling team members to analyze historical data and continuously improve code quality.

[0078] Those skilled in the art will understand that embodiments of this application can be provided as methods, systems, or computer program products. Therefore, this application can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, this application can take the form of a computer program product embodied on one or more computer-readable storage media (including, but not limited to, disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code. This application is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of this application. It will be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, create a machine for implementing the process. Figure 1 One or more processes and / or boxes Figure 1The computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to operate in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The functions specified in one or more boxes. These computer program instructions may also be loaded onto a computer or other programmable data processing apparatus to cause a series of operational steps to be performed on the computer or other programmable apparatus to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable apparatus for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.

[0079] The above description is merely a preferred embodiment of the present invention. The scope of protection of the present invention is not limited to the above embodiments. All technical solutions falling within the scope of the present invention's concept are within the scope of protection of the present invention. It should be noted that for those skilled in the art, any improvements and modifications made without departing from the principles of the present invention should also be considered within the scope of protection of the present invention.

Claims

1. A method for intelligent code review based on a large language model, characterized in that, Includes the following steps: Receive and parse code change events, and add the parsed events to the task queue as review tasks; After retrieving review tasks from the task queue, the code change content is extracted from them. The code change content is then intelligently segmented into different code blocks using AST. The database is used to match the similar historical review records, symbol definitions, and bidirectional call chain information of each code block. The context information weight is dynamically adjusted according to the current review scenario. The code block data, along with the corresponding similar historical review records, symbol definitions, bidirectional call chain information, context information weight, and the scenario type label of the current review scenario, constitute a context data packet. Based on the estimated token demand and the scenario type labels in the context data package, a large language model is selected. Token budget allocation is performed based on the context window limit of the selected large language model and the context information weights in the context data package. Conflict arbitration is performed based on the similar historical review records and bidirectional call chain information in the context data package. Based on the token budget allocation results and conflict arbitration results, the code block data in the context data package, along with the corresponding similar historical review records and symbol definitions, are used to generate optimized prompt words. The optimized prompt words are then input into the large language model for code quality review. After obtaining the review results, a structured review report is generated. Historical review records, symbol definitions, and call chain information from the review reports are added to the database to form an experience loop.

2. The intelligent code review method based on a large language model according to claim 1, characterized in that, The code block is the smallest indivisible syntactic unit. After performing AST intelligent segmentation on the code change content to obtain different code blocks, the following steps are also included: extracting a local symbol table from each syntactic unit to obtain the corresponding set of defined symbols and set of reference symbols, and injecting four-dimensional metadata into each code block. The four-dimensional metadata includes file path, syntax type, start and end line numbers, and change flag. When matching similar historical review records, symbol definitions, and bidirectional call chain information for each code block in the database, the specific steps include: Using the symbol set as the structured query key, dual-path heterogeneous data retrieval is performed; The system iterates through all historical review records in the database, calculates the cosine similarity between the historical review record and the text of the code block, calculates the symbol similarity between the historical review record and the set of symbols defined in the code block, and calculates the file path matching degree between the historical review record and the code block. Based on the cosine similarity, symbol similarity and file path matching degree, the system calculates the comprehensive similarity and selects historical review records with a comprehensive similarity greater than a preset threshold as similar historical review records of the code block. Another approach involves matching the set of reference symbols of the code block in the database to obtain the complete definition code of the reference symbols as the symbol definition. Then, taking the current modified function to which the code block belongs as the center, the call relationship table is matched at a specified depth to obtain the upstream and downstream call chains of the current modified function.

3. The intelligent code review method based on a large language model according to claim 2, characterized in that, The mathematical expression for the overall similarity is as follows: in, Sim sem For cosine similarity, Sim sym For symbol similarity, C path The file path matching score is calculated by comparing the current code block with the file paths in the historical review records, starting from the root directory of the file path. The score is the number of consecutive matching levels divided by the total number of file paths in the current code block. k is the path enhancement index, which defaults to 1. path When k > 0.8, k = 2; γ(t) is the time decay factor, γ(t) = Δt is the number of days since the historical record was written, and λ is the decay coefficient.

4. The intelligent code review method based on a large language model according to claim 3, characterized in that, The context information includes the code block weight W. file Historical record weight W history With symbolic definition of weight W call When dynamically adjusting the weight of contextual information according to the current review scenario, the specific adjustments include: If the current review scenario is a bug fixing scenario, the formula for adjusting the weight of context information is as follows: IN history =1.4 IN hist_base / WITH IN call =0.8 IN sym_base / WITH IN file =0.6 IN chunk_base / WITH If the current review scenario is a new feature scenario, the formula for adjusting the weight of contextual information is as follows: IN call =1.6 IN sym_base / WITH IN history =0.6 IN hist_base / WITH IN file =0.6 IN chunk_base / WITH If the current review scenario is a reconstruction and optimization scenario, the formula for adjusting the weight of context information is as follows: IN call =1.4 IN sym_base / WITH IN file =1.2 IN chunk_base / WITH IN history =0.6 IN hist_base / WITH If the current review scenario is a security scenario, the formula for adjusting the weight of context information is as follows: IN call =2.0 IN sym_base / WITH IN history =0.6 IN hist_base / WITH IN file =0.4 IN chunk_base / WITH In the above formula, Z is the normalization factor. Z = W chunk_base + W hist_base + W sym_base W chunk_base The basic weight of the code block is calculated based on the code block's syntax type, the percentage of lines changed, and the importance of symbols; W hist_base The historical record base weight is the result of multiplying the overall similarity of code blocks by the human feedback factor; W sym_base Define a base weight for the symbol. The base weight for the symbol is calculated by combining the current change function call depth, critical path markers, and dependency breadth of the code block.

5. The intelligent code review method based on a large language model according to claim 4, characterized in that, When selecting a large language model based on the estimated token demand and the scene type labels in the context data package, the specific steps include: Match scene type labels with a pre-defined scene-model matching rule library to filter out a set of candidate model categories; Within the candidate model category set, priority scores for each instance are calculated using a weighted round-robin algorithm based on real-time load, historical success rate, and cost coefficient. The instance with the highest score is selected. If the large language model context window limit of the selected instance is less than the token requirement, the model category of the selected instance is upgraded and the corresponding instance in the candidate model category set is replaced. In the candidate model category set, the step of calculating the priority score of each instance based on real-time load, historical success rate and cost coefficient through a weighted round-robin algorithm is re-executed to reselect the instance.

6. The intelligent code review method based on a large language model according to claim 5, characterized in that, When performing token budget allocation based on the context window constraints of the selected large language model and the weights of context information in the context data packet, the specific steps include: Obtain the selected large language model context window limit as the total token budget; Based on the code block weight, history weight, and symbol definition weight in the context information weights, Softmax normalization is performed to physically isolate the total token budget into mutually exclusive history budget area, symbol definition budget area, and code block budget area.

7. The intelligent code review method based on a large language model according to claim 6, characterized in that, When arbitrating conflicts based on similar historical review records and bidirectional call chain information in the context data packet, the specific steps include: The historical review suggestions with similar historical review records are combined with the call chain structure facts of bidirectional call chain information to form an evidence pair. The large language model is used to extract the operation instructions and their objects in the historical review suggestions, and the dependency state of the objects in the call chain structure facts is extracted. The operation instructions and the dependency state are compared to detect whether there is a conflict. If a conflict is detected, the large language model is invoked to calculate the comprehensive score of the historical review suggestion and the call chain structure facts based on the preset adjudication factors. The arbitration conclusion is determined based on the comparison of the comprehensive scores. The preset adjudication factors include scenario type label, historical credibility, structural constraints, and risk level.

8. The intelligent code review method based on a large language model according to claim 7, characterized in that, Based on the token budget allocation results and conflict arbitration results, when generating optimized prompts by comparing the code block data in the context data package with the corresponding similar historical review records and symbol definitions, the specific steps include: Based on the token budget allocation results, the allocation budgets for the historical record budget area, the symbol definition budget area, and the code block budget area are determined. Estimate the number of tokens required for each of the similar historical review records, the symbol definitions and bidirectional call chain information, and the code block data, and compare the number of tokens required with the allocation budget of the corresponding segment; If the number of tokens used does not exceed the allocation budget of the corresponding segment, the corresponding content will remain intact; if it exceeds the allocation budget of the corresponding segment, the large language model will be invoked to perform semantic compression on the corresponding content, reducing the original content to within the allocation budget of the corresponding segment while retaining the key information required for review. The processed similar history review records are placed in the history budget area, the processed symbol definitions and bidirectional call chain information are placed in the symbol definition budget area, a scenario-based system instruction is generated according to the scenario type label, an arbitration constraint instruction is generated according to the conflict arbitration result, the scenario-based system instruction and the arbitration constraint instruction are injected into the prompt words, and the optimized prompt words are generated.

9. The intelligent code review method based on a large language model according to claim 8, characterized in that, When inputting the optimized prompt words into a large language model for code quality review, the following is included: If a connection timeout, first token timeout, or total generation timeout is triggered, the current large language model instance is abnormal, and it will switch to a backup large language model of the same category to ensure that the session state is not lost. If all alternative large language models in the same category are unavailable, switch to alternative large language models in different categories to ensure that the review process is not interrupted. When the token demand exceeds the context window of the backup large language model, the review content is split into semantically coherent and overlapping sub-fragments based on the AST boundary, and submitted simultaneously to different instances of the backup large language model or different backup large language models through parallel channels for code quality review. The system receives the review results of sub-segments, detects overlapping review comments between sub-segments and removes duplicate suggestions, and combines conflicting comments based on confidence level to form a unified review report.

10. An intelligent code review system based on a large language model, characterized in that, include The multi-platform access module is used to receive and parse code change events, and add the parsed events as review tasks to the task queue. The code parsing and context building module is used to extract code change content from the task queue after obtaining the review task, perform AST intelligent block division on the code change content to obtain different code blocks, match the similar historical review records, symbol definitions and bidirectional call chain information of each code block in the database, dynamically adjust the context information weight according to the current review scenario, and construct a context data packet by combining the code block data with the corresponding similar historical review records, symbol definitions, bidirectional call chain information, context information weight and the scenario type label of the current review scenario. The large language model integration module is used to select a large language model based on the estimated token demand and the scene type label in the context data package. It performs token budget allocation based on the context window limit of the selected large language model and the context information weight in the context data package. It performs conflict arbitration based on the similar historical review records and bidirectional call chain information in the context data package. Based on the token budget allocation result and the conflict arbitration result, it generates optimized prompt words by combining the code block data in the context data package with the corresponding similar historical review records and symbol definitions. The optimized prompt words are then input into the large language model for code quality review. After obtaining the review results, a structured review report is generated. The data storage module is used to add historical review records, symbol definitions, and call chain information from the review report to the database, forming an experience loop.