A code automatic generation method and system based on multi-agent cooperation
Patent Information
- Application Number
- CN202610905403.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-06-23
- Publication Date
- 2026-08-11
AI Technical Summary
传统单智能体代码生成方式受限于模型上下文约束与能力单一性,难以适配复杂、大型、多依赖的工程化代码生成场景,因此多智能体协同生成方案逐步替代传统单模型方案,成为工业级代码自动生成的主流方向
[0044] 1. This invention achieves precise quantification and scenario-based judgment of system load status, solving the problems of traditional scheduling lacking unified quantitative basis and ambiguous condition judgment. This invention constructs a load entropy calculation model, integrating multi-dimensional indicators such as task queues, agent utilization, execution latency, and error rate to achieve a digital representation of system congestion. Simultaneously, it configures differentiated expansion and contraction thresholds for three levels of scenarios: simple functions, single modules, and complex microservice projects. Based on clustering statistics and steady-state condition calibration of threshold parameters, it accurately distinguishes between critical congestion and safe idle states, ensuring the accuracy and rationality of scheduling triggers and fundamentally avoiding technical defects such as delayed expansion and erroneous contraction.
Smart Images

Figure CN122547332A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of intelligent agent collaboration technology, specifically a method and system for automatic code generation based on multi-agent collaboration. Background Technology
[0002] With the rapid development of large language models and artificial intelligence technologies, code generation technology based on multi-agent collaboration has gradually become a research hotspot in the field of intelligent software engineering. By simulating a human development team with specialized agents, it can automate the entire process from requirements analysis, architecture design, code writing, and testing and debugging, effectively improving code development efficiency. Traditional single-agent code generation methods are limited by model context constraints and limited capabilities, making them difficult to adapt to complex, large-scale, and multi-dependency engineering code generation scenarios. Therefore, multi-agent collaborative generation solutions are gradually replacing traditional single-model solutions and becoming the mainstream direction for industrial-grade automatic code generation.
[0003] However, existing multi-agent code generation systems still suffer from numerous core technical deficiencies, severely hindering their practical application. First, current systems often employ a fixed number of agents with fixed roles, failing to adaptively adjust team size based on the actual complexity of the code generation task and the system's real-time load. This results in numerous idle and redundant agents for simple tasks, wasting computing resources, while for complex tasks, insufficient agents and computing congestion lead to a surge in task latency and a decline in code generation quality. Second, existing technologies lack a quantitative evaluation mechanism for the actual working capabilities of each agent, making it impossible to accurately distinguish the code generation capabilities, debugging and repair capabilities, and operational stability of different agents. This results in blindness in agent scheduling, task allocation, and fault replacement, easily leading to unreasonable scheduling problems where high-load, low-capability agents undertake core tasks while high-quality agents remain idle.
[0004] Meanwhile, the existing multi-agent scheduling system lacks a unified load quantification standard, making it impossible to determine the system's congestion and idle / redundant status through refined indicators. The thresholds for scaling up and down are mostly fixed empirical values, without being adapted to different task scenarios, leading to frequent problems such as untimely scaling up in high-load scenarios and erroneous scaling down in low-load scenarios. Summary of the Invention
[0005] The purpose of this invention is to provide a method and system for automatic code generation based on multi-agent collaboration, so as to solve the problems raised in the prior art.
[0006] To achieve the above objectives, the present invention provides the following technical solution: a method for automatic code generation based on multi-agent collaboration, the method comprising the following steps:
[0007] Step S1: Monitor the system with multiple types of intelligent agents covering the entire code lifecycle. The intelligent agents include planning intelligent agents, architecture intelligent agents, coding intelligent agents, testing intelligent agents, and debugging intelligent agents. For the code generation tasks to be executed, collect the task running data of each online intelligent agent and the global load data of the system in real time. Quantify and calculate the current global load entropy of the system through a preset load entropy calculation model. This is used to characterize the degree of system task congestion and the running load status.
[0008] Step S2: Based on the historical execution data and real-time task performance of each agent, dynamically calculate the real-time capability score and capability entropy of each agent through a preset multi-dimensional capability evaluation model; this is used to characterize the code generation capability, debugging and repair capability and operational stability of each agent.
[0009] Step S3: Based on the global load entropy as the scheduling trigger, and based on the capability score and capability entropy of each agent as the agent selection and matching criteria, adaptively execute the elastic scaling up, elastic scaling down and fault replacement operations of the agent team.
[0010] Step S4: Through a preset hot-swappable state transition mechanism, the context synchronization of the agent after elastic scheduling and the alignment of the global project state are completed, so as to maintain the stability of the collaborative operation of the multi-agent team; the agent team after adaptive scheduling will collaboratively complete the entire process of automatic code generation tasks, including code planning, architecture design, code writing, test verification, and vulnerability debugging.
[0011] Furthermore, the current global load entropy of the quantization calculation system includes the following steps:
[0012] Step S11: Collect real-time system performance metrics, including task waiting queue length, task utilization rate of each agent, task execution latency growth rate, and task error rate. Task waiting queue length refers to the real-time cached data of the system's task scheduling queue, representing the total number of subtasks generated from currently queued but unassigned code. Agent task utilization rate is the quotient of the number of tasks currently being executed by each agent and the agent's preset maximum concurrent task capacity, used to characterize the busyness of each agent. Task execution latency growth rate is the difference between the current average execution time of a single task and the historical average execution time of similar tasks, divided by the historical average execution time of similar tasks, characterizing the increasing trend of task execution congestion. Task error rate is the quotient of the number of tasks that failed to execute per unit time and the total number of tasks executed per unit time.
[0013] Step S12: Normalize the above four indicators by their maximum and minimum values to obtain a normalized load feature vector with a value range of [0,1]. Construct a load entropy calculation model based on the information entropy algorithm. The calculation formula is: L E =-∑p i log2(pi ), i∈[1,n],L E This represents the global load entropy, where n is the total number of load metric dimensions, and p... i This represents the weighting of the i-th normalized load metric. A higher load entropy value indicates more severe system congestion and higher agent load.
[0014] Furthermore, the real-time capability score and capability entropy of each agent are dynamically calculated, including the following specific steps:
[0015] Step S21: The multidimensional capability assessment model includes code capability assessment dimension and debugging capability assessment dimension;
[0016] The system obtains the historical task code pass rate, code style score, interface contract consistency score, and task completion rate. The historical task code pass rate is the quotient of the number of tasks that the agent has completed and passed unit tests in the past and the total number of tasks executed by the agent in the past. The code style score is an automatic score given by a preset code style detection model. The detection dimensions include code indentation, comment completeness, naming conventions, and redundant code rate. The output value range is [0,1], which is a standardized score.
[0017] The interface contract consistency score refers to comparing the interface parameters, request methods, and data formats of the agent-generated code with the standard interface contract output by the architecture agent, calculating the matching degree. The matching degree involves extracting the core validation items of the standard interface contract, including five core indicators: request method, parameter name, parameter type, parameter default value, and return data format. The number of compliant indicators in the generated code is counted, and the ratio of the number of compliant indicators to the total number of indicators is normalized to obtain the interface contract consistency score. The task completion rate is the quotient of the number of tasks completed on time to the total number of assigned tasks. Based on the above parameters, the code capability score S for the code capability evaluation dimension is calculated. c S c =w1*P c +w2*S t +w3*S c +w4*R f Where w1, w2, w3, and w4 are preset weight coefficients, and their sum is 1; P c S t S c R f These represent the task code pass rate, code style score, interface contract consistency score, and task completion rate, respectively.
[0018] To obtain historical bug fix success rate, bug location accuracy, and iterative fix efficiency, the historical bug fix success rate is the quotient P of the number of successfully fixed bugs and the total number of bugs handled by the agent. fBug location accuracy refers to the ratio R of the number of successfully located bug root causes to the total number of bugs handled by the agent. p Iterative bug fixing efficiency refers to the quotient E of the standard bug fixing time and the actual bug fixing time of the agent. f Based on the above parameters, the debugging capability score S for the debugging capability evaluation dimension is calculated. d S d =w5*P f +w6*R p +w7*E f , where w5, w6, and w7 represent preset weight coefficients, which sum to 1;
[0019] Step S22: Calculate the agent's overall capability score S, S = α * S c +β*S d α and β are preset weighting coefficients, and their sum is 1; based on the comprehensive ability score of the agent in multiple consecutive tasks, the ability entropy A is calculated. E A E =-∑q k log2(q k ), k∈[1,m], where m is the number of samples in the statistical task, q k This represents the percentage fluctuation in the capability score for the k-th task. A smaller capability entropy indicates a more stable operational capability of the agent.
[0020] Furthermore, the elastic scaling of the adaptive execution agent team includes the following specific aspects:
[0021] Based on the statistical analysis of load entropy data from massive historical code generation tasks, three levels of task scenario thresholds are defined, including Level 1 task scenario threshold v1, Level 2 task scenario threshold v2, and Level 3 task scenario threshold v3. <v2<v3;
[0022] K-means clustering was performed on the load entropy data of normal load, critical congestion load, and severe congestion load under various scenarios to divide the samples into normal operating condition cluster, critical congestion cluster, and severe congestion cluster. The critical entropy value of the two clusters was used as the expansion trigger threshold.
[0023] When the load entropy exceeds the corresponding scenario threshold, obtain the total number T of valid subtasks T in the current system task queue that have a waiting time exceeding a preset threshold and have not been assigned for execution. b The optimal stable concurrent task volume T for each role's intelligent agent based on historical data statistics. s Using the formula: Calculate the number N of new agents required. a γ represents the capacity expansion compensation coefficient. This indicates the rounding up operation;
[0024] First, match the functional roles missing in the current task. Then, from the intelligent agent resource pool of the same role, select the intelligent agent with the highest comprehensive ability score, the lowest ability entropy, and the highest historical completion rate of similar tasks as the expansion instance.
[0025] Furthermore, the elastic scaling-down of the adaptive execution intelligent agent team includes the following:
[0026] Based on the statistics of historical idle and low-load operation data, match the configuration thresholds for the three-level task scenarios, namely the threshold u1 for the first-level task scenario, the threshold u2 for the second-level task scenario, and the threshold u3 for the third-level task scenario, where u1 < u2 < u3; the threshold is set by fitting and calibrating the data of the intelligent agent idle rate, task redundancy, and system computing power utilization rate in each scenario, and taking the critical load entropy value when the overall idle rate of the intelligent agent is ≥ 60%, there is no new task queuing, and the task execution delay is stable at the lowest value as the scaling-down threshold;
[0027] When the load entropy is lower than the critical value of the corresponding scenario, obtain the number Nd of idle intelligent agents in the current system and the minimum number of intelligent agents required for the system to run; based on the above parameters, calculate the number of intelligent agents to be reduced, N e ,N e =N d *ρ, where ρ represents the dynamic scaling coefficient, with a value range of 0.5 - 0.7, and the total number of intelligent agents after scaling-down is not lower than the minimum number of intelligent agents required for the system to run;
[0028] Exclude the core essential intelligent agents of the system, and only include the idle intelligent agents with non-core functional roles in the set to be screened to initialize the screening pool;
[0029] Calculate the scaling-down priority score S for each intelligent agent to be screened cut ,S cut =w8*T0+w9*(1 - S0)+w 10 *A E0 ,where w8, w9, and w 10 are weight coefficients with a sum of 1, T0 represents the normalized idle duration, S0 represents the normalized comprehensive ability score, and A E0 represents the normalized ability entropy; the longer the idle duration, the lower the comprehensive ability score, and the greater the ability entropy of the intelligent agent, the higher the Scut score and the higher the scaling-down priority;
[0030] Sort all the intelligent agents to be screened in descending order of the Scut score, and sequentially select the top Ne intelligent agents as the final scaling-down objects.
[0031] Furthermore, the fault replacement operation of the adaptive execution intelligent agent team includes the following:
[0032] An agent is considered a faulty agent if it experiences any of the following events: multiple consecutive task execution errors, task execution timeouts exceeding a preset threshold, a code test pass rate of zero, or output results conflicting with the global architecture contract.
[0033] For marked faulty agents, a seamless replacement mechanism is triggered to select the best backup agent with the highest comprehensive ability score and the lowest ability entropy from the pool of backup agents with the same role as the replacement instance.
[0034] Terminate the current task of the faulty agent and completely migrate the task context, execution progress, and related dependency data of the faulty agent to the replacement agent.
[0035] Furthermore, step S4 includes the following specific details:
[0036] The pre-defined hot-swappable state migration mechanism refers to the system maintaining a global project state snapshot in real time. This snapshot includes project architecture information, module dependencies, code file data, test report data, and task progress data. When a newly added / replaced agent joins the system, the latest global project state snapshot is automatically loaded, aligning the global view. Individual task contexts are migrated using incremental synchronization, synchronizing only the associated data of incomplete tasks. This avoids the latency and redundancy caused by full data synchronization, ensuring no task interruptions and no data loss during the scheduling process.
[0037] A code generation system based on multi-agent collaboration, comprising a multi-agent cluster, a load-aware computing module, an agent capability assessment module, a dual-entropy linkage elastic scheduling module, and a hot-swappable state transition module.
[0038] The multi-agent cluster includes planning agents, architecture agents, coding agents, testing agents, and debugging agents that work together to cover the entire code generation lifecycle, from code planning and architecture design to code writing, testing and verification, and vulnerability debugging.
[0039] The load-aware computing module is used to collect real-time data on system task queue status, agent utilization, task latency and error rate. It quantifies and outputs the global load entropy of the system through a preset load entropy calculation model, which characterizes the real-time congestion and load status of the system.
[0040] The agent capability evaluation module is used to dynamically calculate the comprehensive capability score and capability entropy of each agent based on its historical task performance and real-time execution effect, from the dimensions of code generation capability, debugging and repair capability, and operational stability, and to complete the quantitative rating of agent capability.
[0041] The dual-entropy linkage elastic scheduling module has preset load entropy thresholds for hierarchical expansion and hierarchical load entropy thresholds. Based on the working condition judgment result of global load entropy, combined with the capability score and capability entropy of each agent, it adaptively completes the dynamic expansion, dynamic reduction and automatic replacement of faulty agents of the agent team.
[0042] The hot-swappable state migration module is used to maintain a global project state snapshot. After the agent elastic scheduling is completed, it completes the global state alignment and task context migration of newly connected agents through incremental synchronization, so that the agent cluster after adaptive scheduling can work together to complete the automatic code generation task of the whole process.
[0043] Compared with the prior art, the beneficial effects of the present invention are:
[0044] 1. This invention achieves precise quantification and scenario-based judgment of system load status, solving the problems of traditional scheduling lacking unified quantitative basis and ambiguous condition judgment. This invention constructs a load entropy calculation model, integrating multi-dimensional indicators such as task queues, agent utilization, execution latency, and error rate to achieve a digital representation of system congestion. Simultaneously, it configures differentiated expansion and contraction thresholds for three levels of scenarios: simple functions, single modules, and complex microservice projects. Based on clustering statistics and steady-state condition calibration of threshold parameters, it accurately distinguishes between critical congestion and safe idle states, ensuring the accuracy and rationality of scheduling triggers and fundamentally avoiding technical defects such as delayed expansion and erroneous contraction.
[0045] 2. A comprehensive multi-dimensional capability quantitative evaluation system for intelligent agents has been constructed, solving the problems of traditional technologies being unable to distinguish the true capabilities and stability of intelligent agents and having strong blind scheduling. This invention constructs a comprehensive capability scoring system from two dimensions: code generation capability and debugging and repair capability. It refines multi-level quantitative indicators such as code standardization, interface consistency, bug fix rate, and execution efficiency. At the same time, capability entropy is introduced to characterize the working stability of intelligent agents, realizing the digital and differentiated rating of the capabilities of all intelligent agents. This provides accurate data support for intelligent agent selection, task matching, and fault replacement, and significantly improves the collaborative adaptability of multi-agent teams.
[0046] 3. This invention addresses the core pain points of traditional fixed agent architectures: "wasteful resources for simple tasks, insufficient computing power for complex tasks, and increasingly chaotic collaboration as the team grows larger." Based on load entropy-triggered scheduling, this invention leverages agent capability scores and capability entropy to achieve refined scaling and fault replacement. It can dynamically adjust the agent team size according to task complexity, accurately selecting high-capability, high-stability agents to undertake core tasks and eliminating low-capability, high-fluctuation redundant agents. This achieves dynamic optimal allocation of computing resources, effectively reducing collaboration complexity and resource consumption, and improving the execution efficiency of complex code generation tasks. Attached Figure Description
[0047] Figure 1 This is a schematic diagram of the structure of an automatic code generation method based on multi-agent collaboration according to the present invention. Detailed Implementation
[0048] Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0049] Example: Figure 1 As shown, to achieve the above objectives, the present invention provides the following technical solution: a method for automatic code generation based on multi-agent collaboration, the method comprising the following steps:
[0050] Step S1: Monitor the system with multiple types of intelligent agents covering the entire code lifecycle. The intelligent agents include planning intelligent agents, architecture intelligent agents, coding intelligent agents, testing intelligent agents, and debugging intelligent agents. For the code generation tasks to be executed, collect the task running data of each online intelligent agent and the global load data of the system in real time. Quantify and calculate the current global load entropy of the system through a preset load entropy calculation model. This is used to characterize the degree of system task congestion and the running load status.
[0051] Step S2: Based on the historical execution data and real-time task performance of each agent, dynamically calculate the real-time capability score and capability entropy of each agent through a preset multi-dimensional capability evaluation model; this is used to characterize the code generation capability, debugging and repair capability and operational stability of each agent.
[0052] Step S3: Based on the global load entropy as the scheduling trigger, and based on the capability score and capability entropy of each agent as the agent selection and matching criteria, adaptively execute the elastic scaling up, elastic scaling down and fault replacement operations of the agent team.
[0053] Step S4: Through a preset hot-swappable state transition mechanism, the context synchronization of the agent after elastic scheduling and the alignment of the global project state are completed, so as to maintain the stability of the collaborative operation of the multi-agent team; the agent team after adaptive scheduling will collaboratively complete the entire process of automatic code generation tasks, including code planning, architecture design, code writing, test verification, and vulnerability debugging.
[0054] The current global load entropy of the quantization calculation system includes the following steps:
[0055] Step S11: Collect real-time system performance metrics, including task waiting queue length, task utilization rate of each agent, task execution latency growth rate, and task error rate. Task waiting queue length refers to the real-time cached data of the system's task scheduling queue, representing the total number of subtasks generated from currently queued but unassigned code. Agent task utilization rate is the quotient of the number of tasks currently being executed by each agent and the agent's preset maximum concurrent task capacity, used to characterize the busyness of each agent. Task execution latency growth rate is the difference between the current average execution time of a single task and the historical average execution time of similar tasks, divided by the historical average execution time of similar tasks, characterizing the increasing trend of task execution congestion. Task error rate is the quotient of the number of tasks that failed to execute per unit time and the total number of tasks executed per unit time.
[0056] Step S12: Normalize the above four indicators by their maximum and minimum values to obtain a normalized load feature vector with a value range of [0,1]. Construct a load entropy calculation model based on the information entropy algorithm. The calculation formula is: L E =-∑p i log2(p i ), i∈[1,n],L E This represents the global load entropy, where n is the total number of load metric dimensions, and p... i This represents the weighting of the i-th normalized load metric. A higher load entropy value indicates more severe system congestion and higher agent load.
[0057] The real-time capability score and capability entropy of each agent are dynamically calculated, including the following specific steps:
[0058] Step S21: The multidimensional capability assessment model includes code capability assessment dimension and debugging capability assessment dimension;
[0059] The system obtains the historical task code pass rate, code style score, interface contract consistency score, and task completion rate. The historical task code pass rate is the quotient of the number of tasks that the agent has completed and passed unit tests in the past and the total number of tasks executed by the agent in the past. The code style score is an automatic score given by a preset code style detection model. The detection dimensions include code indentation, comment completeness, naming conventions, and redundant code rate. The output value range is [0,1], which is a standardized score.
[0060] As shown in the example: the code indentation compliance score adopts a line-by-line standardized deduction system, based on the project's unified preset indentation specifications, including 4 spaces as the first level of indentation, prohibition of tab indentation, and progressively increasing nested indentation levels. The code indentation compliance score is calculated by subtracting the number of indentation violation lines from the total number of valid code lines. Single violations include: incorrect number of indentation spaces, mixed use of tabs and spaces, disordered nested indentation levels, and no indentation of conditional / loop statement blocks.
[0061] The completeness score is calculated by dividing the number of valid comments that are complete, accurate, and free of invalid placeholder characters by the total number of code units that need to be annotated. Code units that need to be annotated include all functions, classes, core logic blocks, and branch judgment logic. Comments without missing key logic, blank comments, or perfunctory characters are considered valid.
[0062] The naming standard score is calculated by subtracting the number of non-standard identifiers from the total number of identifiers for all variables, functions, classes, and constants in the code. Violations include capitalization errors, semantically confusing names, using pinyin, meaningless single-character names, and improper use of underscores.
[0063] The score for low redundancy code is calculated by subtracting the number of redundant lines from the total number of valid lines. Redundant code includes repetitive logic, invalid assignments, invalid imports, dead code that can never be executed, and duplicate conditional statements. The lower the redundancy rate, the higher the score in this dimension.
[0064] The scores of all four sub-dimensions are normalized to [0,1], and the final average value is used to obtain the code standardization score. The lower the redundancy rate, the higher the format compliance, the more complete the comments, and the more standardized the naming, the higher the corresponding code standardization score.
[0065] The interface contract consistency score refers to comparing the interface parameters, request methods, and data formats of the agent-generated code with the standard interface contract output by the architecture agent, calculating the matching degree. The matching degree involves extracting the core validation items of the standard interface contract, including five core indicators: request method, parameter name, parameter type, parameter default value, and return data format. The number of compliant indicators in the generated code is counted, and the ratio of the number of compliant indicators to the total number of indicators is normalized to obtain the interface contract consistency score. The task completion rate is the quotient of the number of tasks completed on time to the total number of assigned tasks. Based on the above parameters, the code capability score S for the code capability evaluation dimension is calculated. c S c =w1*P c +w2*S t +w3*S c +w4*R f Where w1, w2, w3, and w4 are preset weight coefficients, and their sum is 1; P c S t S c R f These represent the task code pass rate, code style score, interface contract consistency score, and task completion rate, respectively.
[0066] Obtain the historical bug repair success rate, bug location accuracy rate, and iterative repair efficiency. The historical bug repair success rate is the quotient P of the number of successfully repaired bugs and the total number of bugs received by the agent. f The bug location accuracy rate is the quotient R of the number of bugs whose root causes are successfully located and the total number of bugs received by the agent. p The iterative repair efficiency is the quotient E of the standard repair duration of the same type of bugs and the actual repair duration of the agent. f Calculate the debugging ability score S of the debugging ability evaluation dimension based on the above parameters. d S d = w5 * P f + w6 * R p + w7 * E f where w5, w6, and w7 represent preset weight coefficients, and the sum is 1.
[0067] Step S22: Calculate the comprehensive ability score S of the agent, S = ɑ * S c + β * S d where ɑ and β are preset weight coefficients, and the sum is 1. Calculate the ability entropy A based on the comprehensive ability scores of the agent's consecutive multiple tasks. E A E =-∑q k log2(q k ), k ∈ [1, m], where m is the number of statistical task samples, and q k is the fluctuation proportion of the k-th task ability score. The smaller the ability entropy, the more stable the operation ability of the agent is characterized.
[0068] The elastic expansion of the adaptive execution agent team includes the following specific contents:
[0069] Based on the load entropy data statistics of a large number of historical code generation tasks, divide the three-level task scenario thresholds, including the first-level task scenario threshold v1, the second-level scenario task threshold v2, and the third-level scenario task threshold v3, where v1 < v2 < v3; the larger the task scenario threshold, the greater the development difficulty of the corresponding scenario.
[0070] Perform Kmeans clustering on the load entropy data of normal load, congestion critical load, and severe congestion load in each scenario, divide the samples into normal working condition clusters, critical congestion clusters, and severe congestion clusters, and obtain the segmentation critical entropy value of the two types of clusters as the expansion trigger threshold.
[0071] The clustering process includes: setting the number of cluster centers K=3, representing three system operating states; cluster 0: normal load, cluster 1: critical congestion, cluster 2: severe congestion; calculating the Euclidean distance between each sample and the three cluster centers, and assigning the sample to the nearest cluster; taking the mean of all samples in each cluster to generate new cluster centers; repeating steps 1-2 until the cluster centers no longer change, and the clustering is complete; finally outputting 3 clusters + the center load entropy value of each cluster + the inter-cluster boundary value; automatically labeling the operating conditions according to the index characteristics of each cluster; taking the intermediate boundary value between the normal load cluster - cluster 0 and the critical congestion cluster - cluster 1 as the expansion load entropy threshold for this scenario.
[0072] As shown in the example: the three-dimensional quantization triggering conditions for entering a critical congestion state are determined. If any two conditions are met, it is determined to be a congestion critical point, as detailed below:
[0073] A current task delay growth rate of 20% or more indicates a significant increase in task time compared to the historical steady-state baseline, resulting in congested delays.
[0074] The average task utilization rate of the intelligent agent is greater than or equal to 85%, and the overall intelligent agent is close to the computing power limit, with no spare computing power to take on new tasks.
[0075] The instantaneous task error rate is more than 15% higher than the steady-state error rate. Excessive load can lead to increased hallucinations, code generation failures, and interface matching errors.
[0076] By jointly calibrating the critical load entropy of each scenario using the above three quantitative indicators, the threshold is ensured to fit the load mutation boundary of each scenario. The threshold setting is based on the following: when the load entropy exceeds the critical value of the corresponding scenario, the system task congestion, agent utilization, and task latency will increase exponentially, making it impossible to guarantee code generation efficiency and quality. This serves as the critical condition for capacity expansion.
[0077] Generally, Level 1 task scenarios represent simple function generation scenarios, Level 2 task scenarios represent single-module development scenarios, and Level 3 task scenarios represent complex microservice projects.
[0078] When the load entropy exceeds the corresponding scenario threshold, obtain the total number T of valid subtasks T in the current system task queue that have a waiting time exceeding a preset threshold and have not been assigned for execution. b The optimal stable concurrent task volume T for each role's intelligent agent based on historical data statistics. s The coding agent, debugging agent, and testing agent are configured with fixed standard values as needed; using the formula: Calculate the number N of new agents required. a γ represents the capacity expansion compensation coefficient, with a value range of [1.1, 1.3]. This indicates the rounding up operation;
[0079] Prioritize matching the missing functional roles of the current task, and then screen the agent with the highest comprehensive ability score, the smallest ability entropy, and the highest historical completion rate of the same type of tasks from the intelligent agent resource pool of the same role as the expansion instance.
[0080] The elastic scaling down of the adaptive execution intelligent agent team includes the following:
[0081] Based on the statistics of historical idle and low-load operation data, match the configuration thresholds of the three-level task scenarios, the threshold u1 of the first-level task scenario, the threshold u2 of the second-level task scenario, and the threshold u3 of the third-level task scenario, where u1 < u2 < u3; the threshold is set based on the fitting calibration of the agent idle rate, task redundancy, and system computing power utilization data in each scenario, and the critical load entropy value when the overall agent idle rate ≥ 60%, no new tasks are queued, and the task execution delay is stable at the lowest value is taken as the scaling-down threshold;
[0082] As shown in the embodiment: The lowest stable value of the task execution delay is the system steady-state reference delay. The specific acquisition method is to screen all historical steady-state operation samples without task queuing, agent utilization ≤ 40%, and no error retry for a single task scenario, and剔除 congestion samples, sudden fluctuation samples, and abnormal timeout samples; use sliding window variance filtering, set a fixed-time sliding window, and calculate the task delay variance for each window; retain the convergent steady-state samples with window delay variance less than the preset fluctuation threshold, and filter out instantaneous jitter data; count the task execution time of all convergent steady-state samples, and calculate the sample mean as the scenario reference steady-state delay;
[0083] The threshold is set based on: when the load entropy is lower than the critical value of the corresponding scenario, the idle rate of the system agents exceeds 60%, the task execution time is close to the lowest stable value of the delay, there is a large amount of computing power redundancy and resource waste in the system, and there is no risk of immediate task congestion, so the scaling-down operation can be safely performed;
[0084] Lock the safe scaling-down intervals for each scenario; the quantitative determination of each level scenario includes a simple function generation scenario: single task, short execution cycle, global load entropy < 0.1, agents are idle for a long time, triggering scaling down; single-module development scenario: module development completed, no iterative optimization tasks, global load entropy < 0.2, most functional agents are idle, triggering scaling down; microservice complex project scenario: core module development completed, only a small number of finishing tasks remaining, global load entropy < 0.3, a large number of auxiliary agents have no task scheduling, triggering scaling down;
[0085] When the load entropy is lower than the critical value of the corresponding scenario, obtain the current number of idle agents Nd in the system and the minimum number of agents required for the system to run; the minimum number of agents required for the system to run is a preset fixed threshold, which is the minimum number of agents to ensure the basic collaborative ability of the system, including the necessary planning agents and core roles of the architecture agents, and cannot be reduced; based on the above parameters, calculate the number of agents to be reduced, Ne N e =N d *ρ, where ρ represents the dynamic scaling-down coefficient, ranging from 0.5 to 0.7, and the total number of agents after scaling-down is not less than the minimum number of agents required for system operation;
[0086] Remove the core essential intelligent agents of the system and only include idle intelligent agents with non-core functional roles into the set to be screened to initialize the screening pool;
[0087] Calculate the scaling priority score S for each agent to be selected. cut S cut =w8*T0+w9*(1-S0)+w 10 *A E0 Among them, w8, w9, w 10 The weighted coefficients are summed to 1, T0 represents the normalized idle time, S0 represents the normalized comprehensive ability score, and A... E0 The normalized capability entropy represents the agent with the longer idle time, the lower the overall capability score, and the higher the capability entropy. The higher the Scut score, the higher the shrinkage priority.
[0088] All agents to be screened are sorted in descending order of their Scut scores, and the top Ne agents are selected as the final shrinking targets.
[0089] The adaptive fault-finding operations of the intelligent agent team include the following:
[0090] An agent is considered a faulty agent if it experiences any of the following events: multiple consecutive task execution errors, task execution timeouts exceeding a preset threshold, a code test pass rate of zero, or output results conflicting with the global architecture contract.
[0091] For marked faulty agents, a seamless replacement mechanism is triggered to select the best backup agent with the highest comprehensive ability score and the lowest ability entropy from the pool of backup agents with the same role as the replacement instance.
[0092] Terminate the current task of the faulty agent and completely migrate the task context, execution progress, and related dependency data of the faulty agent to the replacement agent.
[0093] Step S4 includes the following specific contents:
[0094] The pre-defined hot-swappable state migration mechanism refers to the system maintaining a global project state snapshot in real time. This snapshot includes project architecture information, module dependencies, code file data, test report data, and task progress data. When a newly added / replaced agent joins the system, the latest global project state snapshot is automatically loaded, aligning the global view. Individual task contexts are migrated using incremental synchronization, synchronizing only the associated data of incomplete tasks. This avoids the latency and redundancy caused by full data synchronization, ensuring no task interruptions and no data loss during the scheduling process.
[0095] A code generation system based on multi-agent collaboration, comprising a multi-agent cluster, a load-aware computing module, an agent capability assessment module, a dual-entropy linkage elastic scheduling module, and a hot-swappable state transition module.
[0096] The multi-agent cluster includes planning agents, architecture agents, coding agents, testing agents, and debugging agents that work together to cover the entire code generation lifecycle, from code planning and architecture design to code writing, testing and verification, and vulnerability debugging.
[0097] The load-aware computing module is used to collect real-time data on system task queue status, agent utilization, task latency and error rate. It quantifies and outputs the global load entropy of the system through a preset load entropy calculation model, which characterizes the real-time congestion and load status of the system.
[0098] The agent capability evaluation module is used to dynamically calculate the comprehensive capability score and capability entropy of each agent based on its historical task performance and real-time execution effect, from the dimensions of code generation capability, debugging and repair capability, and operational stability, and to complete the quantitative rating of agent capability.
[0099] The dual-entropy linkage elastic scheduling module has preset load entropy thresholds for hierarchical expansion and hierarchical load entropy thresholds. Based on the working condition judgment result of global load entropy, combined with the capability score and capability entropy of each agent, it adaptively completes the dynamic expansion, dynamic reduction and automatic replacement of faulty agents of the agent team.
[0100] The hot-swappable state migration module is used to maintain a global project state snapshot. After the agent elastic scheduling is completed, it completes the global state alignment and task context migration of newly connected agents through incremental synchronization, so that the agent cluster after adaptive scheduling can work together to complete the automatic code generation task of the whole process.
[0101] Finally, it should be noted that the above descriptions are merely preferred embodiments of the present invention and are not intended to limit the present invention. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art can still modify the technical solutions described in the foregoing embodiments or make equivalent substitutions for some of the technical features. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the protection scope of the present invention.
Claims
1. A method for automatic code generation based on multi-agent collaboration, characterized in that: The method includes the following steps: Step S1: Monitor the system configured with multiple types of intelligent agents covering the entire code lifecycle. The intelligent agents include planning intelligent agents, architecture intelligent agents, coding intelligent agents, testing intelligent agents, and debugging intelligent agents. For the code generation task to be executed, collect the task running data of each online intelligent agent and the global load data of the system in real time. Quantitatively calculate the current global load entropy of the system using a preset load entropy calculation model. Step S2: Based on the historical execution data and real-time task performance of each agent, dynamically calculate the real-time capability score and capability entropy of each agent through a preset multi-dimensional capability evaluation model; Step S3: Using the global load entropy as the scheduling trigger, and the capability score and capability entropy of each agent as the agent selection and matching criteria, adaptively execute the elastic scaling up, elastic scaling down, and fault replacement operations of the agent team. Step S4: Through a preset hot-swappable state transition mechanism, complete the context synchronization of the agent after elastic scheduling and the alignment of the global project state; the agent team after adaptive scheduling will collaboratively complete the entire process of automatic code generation tasks, including code planning, architecture design, code writing, test verification, and vulnerability debugging.
2. The method for automatic code generation based on multi-agent collaboration according to claim 1, characterized in that: The current global load entropy of the quantization calculation system includes the following steps: Step S11: Collect real-time system performance metrics, including task waiting queue length, task utilization rate of each agent, task execution latency growth rate, and task error rate. The task waiting queue length refers to the real-time cached data of the system's task scheduling queue, representing the total number of subtasks generated from currently queued but unassigned code. The agent task utilization rate is the quotient of the number of tasks currently being executed by each agent and the agent's preset maximum concurrent task capacity. The task execution latency growth rate is the difference between the current average execution time of a single task and the historical average execution time of the same type of task, divided by the historical average execution time of the same type of task. The task error rate is the quotient of the number of tasks that failed to execute per unit time and the total number of tasks executed per unit time. Step S12: Normalize the above four indicators by their maximum and minimum values to obtain a normalized load feature vector with a value range of [0,1]. Construct a load entropy calculation model based on the information entropy algorithm. The calculation formula is: L E =-∑p i log2(p i ), i∈[1,n],L E This represents the global load entropy, where n is the total number of load metric dimensions, and p... i This represents the weight of the i-th normalized load metric.
3. The method for automatic code generation based on multi-agent collaboration according to claim 1, characterized in that: The dynamic calculation of the real-time capability score and capability entropy of each agent includes the following specific steps: Step S21: The multidimensional capability assessment model includes a code capability assessment dimension and a debugging capability assessment dimension; The system obtains the historical task code pass rate, code style score, interface contract consistency score, and task completion rate. The historical task code pass rate is the quotient of the number of tasks that the agent has completed and passed unit tests in the past and the total number of tasks executed by the agent in the past. The code style score is a standardized score automatically assigned by a preset code style detection model. The detection dimensions include code indentation, comment completeness, naming conventions, and redundant code rate. The output value range is [0,1]. The interface contract consistency score refers to calculating the matching degree by comparing the interface parameters, request methods, and data formats of the code generated by the intelligent agent with the standard interface contract output by the architecture intelligent agent. The matching degree refers to extracting the core verification items of the standard interface contract, and the core verification items include five core indicators: request method, parameter name, parameter type, parameter default value, and return data format. Count the number of compliant indicators in the generated code, normalize the ratio of the number of compliant indicators to the total number of indicators, and use it as the interface contract consistency score; The task completion rate refers to the quotient of the number of tasks completed on time to the total number of tasks assigned; based on the above parameters, the code capability score S for the code capability assessment dimension is calculated. c S c =w1*P c +w2*S t +w3*S c +w4*R f Where w1, w2, w3, and w4 are preset weight coefficients, and their sum is 1; P c S t S c R f These represent the task code pass rate, code style score, interface contract consistency score, and task completion rate, respectively. The project obtains historical bug fix success rate, bug location accuracy, and iterative fix efficiency. The historical bug fix success rate is defined as the quotient P of the number of successfully fixed bugs and the total number of bugs handled by the agent. f The bug location accuracy refers to the quotient R of the number of successfully located bug root causes to the total number of bugs handled by the agent. p The iterative repair efficiency refers to the quotient E of the standard repair time for the same type of bug and the actual repair time of the agent. f Based on the above parameters, the debugging capability score S for the debugging capability evaluation dimension is calculated. d S d =w5*P f +w6*R p +w7*E f , where w5, w6, and w7 represent preset weight coefficients, which sum to 1; Step S22: Calculate the agent's overall capability score S, S = α * S c +β*S d α and β are preset weighting coefficients, and their sum is 1; based on the comprehensive ability score of the agent in multiple consecutive tasks, the ability entropy A is calculated. E A E =-∑q k log2(q k ), k∈[1,m], where m is the number of samples in the statistical task, q k This represents the percentage fluctuation in the ability score for the k-th task.
4. The method for automatic code generation based on multi-agent collaboration according to claim 1, characterized in that: The elastic expansion of the adaptive execution intelligent agent team includes the following specific contents: Based on the statistical analysis of the load entropy data of a large number of historical code generation tasks, divide the three-level task scenario thresholds, including the first-level task scenario threshold v1, the second-level task scenario threshold v2, and the third-level task scenario threshold v3, where v1 < v2 < v3; Perform Kmeans clustering on the load entropy data of normal load, congestion critical load, and severe congestion load in each scenario, divide the samples into normal working condition clusters, critical congestion clusters, and severe congestion clusters, and obtain the segmentation critical entropy value of the two types of clusters as the expansion trigger threshold; When the load entropy exceeds the corresponding scenario threshold, obtain the total number T of valid subtasks T in the current system task queue that have a waiting time exceeding a preset threshold and have not been assigned for execution. b The optimal stable concurrent task volume T for each role's intelligent agent based on historical data statistics. s Using the formula: Calculate the number N required to add intelligent agents. a γ represents the capacity expansion compensation coefficient. This indicates the rounding up operation; First, match the missing functional roles of the current task, and then select the intelligent agent with the highest comprehensive ability score, the smallest ability entropy, and the highest historical completion rate of the same type of task from the intelligent agent resource pool of the same role as the expansion instance.
5. The method for automatic code generation based on multi-agent collaboration according to claim 1, characterized in that: The elastic contraction of the adaptive execution intelligent agent team includes the following contents: Based on the statistical analysis of historical idle and low-load operation data, match the three-level task scenario configuration thresholds, the first-level task scenario threshold u1, the second-level task scenario threshold u2, and the third-level task scenario threshold u3, where u1 < u2 < u3; The threshold setting is based on the fitting calibration of the intelligent agent idle rate, task redundancy, and system computing power utilization data in each scenario, and take the critical load entropy value corresponding to the overall idle rate of the intelligent agent ≥ 60%, no new task queue, and the lowest stable task execution delay as the contraction threshold; When the load entropy is lower than the corresponding scenario threshold, obtain the current number of idle agents Nd and the minimum number of running agents in the system; based on the above parameters, calculate the number of agents to be reduced, Nd. e N e =N d *ρ, where ρ represents the dynamic scaling-down coefficient, ranging from 0.5 to 0.7, and the total number of agents after scaling-down is not less than the minimum number of agents required for system operation; Exclude the core essential intelligent agents of the system, and only include the idle intelligent agents of non-core functional roles in the待筛选集合 (to be screened set) to initialize the screening pool; Calculate the scaling priority score S for each agent to be selected. cut S cut =w8*T0+w9*(1-S0)+w 10 *A E0 Among them, w8, w9, w 10 The weighted coefficients are summed to 1, T0 represents the normalized idle time, S0 represents the normalized comprehensive ability score, and A... E0 Represents the normalization capability entropy; Sort all the待筛选智能体 (to be screened intelligent agents) in descending order according to the Scut score, and select the first Ne intelligent agents in turn as the final contraction objects.
6. The method for automatic code generation based on multi-agent collaboration according to claim 1, characterized in that: The fault replacement operation of the adaptive execution intelligent agent team includes the following contents: When any one of the events such as continuous task execution errors of the intelligent agent, task execution timeout exceeding the preset threshold, code test pass rate being zero, and output result conflicting with the global architecture contract occurs, it is determined as a faulty intelligent agent; For the marked faulty intelligent agent, trigger the seamless replacement mechanism, and select the optimal backup intelligent agent with the highest comprehensive ability score and the smallest ability entropy from the backup intelligent agent pool of the same role as the replacement instance; Terminate the current task of the faulty intelligent agent, and completely migrate the task context, execution progress, and associated dependency data of the faulty intelligent agent to the replacement intelligent agent.
7. The method for automatic code generation based on multi-agent collaboration according to claim 1, characterized in that: The step S4 includes the following specific contents: The preset hot-swap state migration mechanism refers to the system maintaining a global project state snapshot in real time. The snapshot includes project architecture information, module dependencies, code file data, test report data, and task progress data. After a newly expanded / replaced agent is connected to the system, the latest global project state snapshot is automatically loaded to complete the global view alignment. Individual task contexts are migrated using an incremental synchronization method, synchronizing only the associated data of incomplete tasks.
8. A code generation system based on multi-agent cooperation, using the code generation method based on multi-agent cooperation as described in any one of claims 1-7, characterized in that: The system includes a multi-agent cluster, a load-aware computing module, an agent capability evaluation module, a dual-entropy linkage elastic scheduling module, and a hot-swappable state transition module. The multi-agent cluster includes planning agents, architecture agents, coding agents, testing agents, and debugging agents that work together to cover the entire code generation lifecycle, from code planning and architecture design to code writing, testing and verification, and vulnerability debugging. The load perception computing module is used to collect real-time system task queue status, agent utilization, task latency and error rate data, and quantifies the global load entropy of the system through a preset load entropy calculation model to characterize the real-time congestion and load status of the system. The agent capability evaluation module is used to dynamically calculate the comprehensive capability score and capability entropy of each agent based on its historical task performance and real-time execution effect, from the dimensions of code generation capability, debugging and repair capability, and operational stability, and to complete the quantitative rating of agent capability. The dual-entropy linkage elastic scheduling module is preset with a tiered expansion load entropy threshold and a tiered reduction load entropy threshold. Based on the working condition judgment result of the global load entropy, combined with the capability score and capability entropy of each agent, it adaptively completes the dynamic expansion, dynamic reduction and automatic replacement of faulty agents of the agent team. The hot-swappable state migration module is used to maintain a global project state snapshot. After the agent elastic scheduling is completed, it completes the global state alignment and task context migration of the newly connected agent through incremental synchronization, so that the agent cluster after adaptive scheduling can collaboratively complete the full-process automatic code generation task.