Code generation method, power distribution network fault monitoring method, equipment, medium and product
By semantically parsing and decomposing the code generation instructions input by users, and combining pre-compiled code and intelligent agent generation methods, the problem that traditional methods are difficult to handle complex programming tasks is solved, and efficient automated processing of power distribution network fault monitoring is achieved.
Patent Information
- Application Number
- CN202610007175.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-01-05
- Publication Date
- 2026-02-03
AI Technical Summary
Traditional code generation methods struggle to handle complex programming tasks involving multi-module collaboration and strategy selection, especially in power distribution network fault monitoring, where they are unable to achieve automatic and rapid fault location and power restoration.
The code generation instructions input by the user are semantically parsed and decomposed into multiple subtasks. An appropriate code generation method is selected according to the complexity of each subtask, including using pre-compiled code, agent generation, or code generation combined with user preferences.
It enables the decomposition of complex tasks and efficient code generation, improving the automation level and fault handling efficiency of power distribution network fault monitoring.
Smart Images

Figure CN121455495A_ABST
Abstract
Description
Technical Field
[0001] This disclosure relates to the field of code generation technology, and in particular to a code generation method, a power distribution network fault monitoring method, equipment, medium and product. Background Technology
[0002] With the continuous development of computer technology, various types of automatic code generation methods have been developed, such as reusing historical code and generating code according to preset rules.
[0003] The key to automated code generation lies in accurately understanding the intent of users or developers and generating reliable and efficient code. The challenge lies in the deep semantic understanding, strategy planning capabilities, and controllability of the generation process required to handle high-level, multi-dimensional, and complex tasks. However, traditional code generation methods often focus on generating code snippets, lacking the ability to coordinate the overall task architecture and strategy logic, making it difficult to handle complex programming tasks that require multi-module collaboration and strategy selection.
[0004] For example, taking power distribution network fault monitoring technology as an example, when a power distribution line fails, the power distribution network fault monitoring system needs to be able to automatically and quickly determine the location of the fault, restore power supply to the fault area, and ensure normal power supply to the non-fault area. This process involves multiple decision-making stages and requires comprehensive consideration of factors such as different types of faults and power demand in different areas. Traditional code generation schemes are difficult to support the code generation of such a complex system, and manual completion of system building and configuration is still required. Summary of the Invention
[0005] This disclosure provides a code generation method, a power distribution network fault monitoring method, equipment, medium, and product, to at least address the problem that traditional code generation schemes are unable to handle complex code generation tasks. The technical solution of this disclosure is as follows: According to a first aspect of this disclosure, a code generation method is provided, the code generation method comprising: responding to receiving a code generation instruction input by a user, performing semantic parsing on the code generation instruction, wherein the code generation instruction includes a code generation task described in natural language; decomposing the code generation task into multiple subtasks based on the result of the semantic parsing; for each subtask, determining a code generation method for executing the subtask based on the task complexity of the subtask, so as to generate code for the subtask, wherein the task complexity characterizes the difficulty of executing the code generation task; and generating code for the code generation task based on the code generated for each subtask.
[0006] As an example, for each subtask, the code generation method is determined as follows: the current subtask is matched with pre-compiled code to obtain a matching result; the code generation method is determined based on the task complexity of the current subtask and the matching result.
[0007] As an example, the task complexity includes strategy complexity and computational complexity. The strategy complexity represents the decision-making level required to generate code, and the computational complexity represents the computational resources and time required to generate code. The step of determining the code generation method based on the task complexity of the current subtask and the matching result includes: generating code for the current subtask based on the pre-compiled code in response to the matching result indicating that the matching degree between the current subtask and at least one of the pre-compiled codes is higher than or equal to a preset degree; and determining the code generation method based on the strategy complexity and the computational complexity in response to the matching result indicating that the matching degree between the current subtask and all pre-compiled codes is lower than the preset degree.
[0008] As an example, determining the code generation method based on the policy complexity and the computational complexity includes: generating code for the current subtask based on the pre-compiled code in response to the policy complexity being lower than or equal to a first threshold; generating code based on the task preference of the subtask in response to the policy complexity being higher than the first threshold and lower than or equal to a second threshold, and the computational complexity being lower than or equal to a third threshold, wherein the task preference represents the user's tendency to perform the current subtask; and generating code for the current subtask using an agent for generating code in response to the policy complexity being higher than the second threshold or the computational complexity being higher than the third threshold.
[0009] As an example, the code generation method includes at least one of the following: generating code based on pre-compiled code; generating code according to the task preferences of a subtask, wherein the task preferences represent the user's inclination to perform the current subtask; and generating code using an agent for generating code.
[0010] As an example, the code generation based on pre-compiled code includes: selecting target code for executing the current subtask from multiple pre-compiled codes; analyzing the difference between the code function of the target code and the task requirements of the current subtask to obtain an analysis result; in response to the analysis result indicating that the difference is lower than or equal to a preset difference level, using the target existing code as the code for the current subtask; in response to the analysis result indicating that the difference is higher than the preset difference level, identifying local code in the target existing code that differs from the task requirements, using an intelligent agent to modify the local code according to the task requirements, and using the modified target existing code as the code for the current subtask.
[0011] As an example, the target code is selected as follows: The historical call success rate and execution efficiency index of each precompiled code are obtained from the code knowledge base, wherein the historical call success rate represents the success rate of the precompiled code being called in historical tasks, and the execution efficiency index represents the computation time and resource requirements of the precompiled code; based on the historical call success rate and the execution efficiency index of each precompiled code, the performance weight of that precompiled code is determined; based on the performance weight of each precompiled code and its matching degree with the current subtask, the retrieval score of that precompiled code is determined; and based on the retrieval scores of each precompiled code in the code knowledge base, the target code for executing the current subtask is selected.
[0012] As an example, the step of generating code based on the task preferences of a subtask includes: identifying the task preferences of the current subtask based on the result of the semantic parsing to obtain a preference score, wherein the preference score is a quantitative representation of the task preference; in response to the preference score being greater than or equal to a preset value, generating code for the current subtask in the following manner: converting the task information of the current subtask into a preference parameter vector, wherein the preference parameter vector is a quantitative representation of the semantics related to the task preference in the task information; based on the current preference parameter vector, obtaining a target strategy template matching the preference parameter vector from a plurality of preset strategy templates, wherein each strategy template in the plurality of strategy templates is labeled with the strategy. The range of the preference parameter vector corresponding to the target, each policy template contains prompts related to the range of the corresponding preference parameter vector; using an agent, based on the preference parameter vector and the target policy template, the agent generates the code for the current subtask; in response to the preference score being less than the preset value, the code for the current subtask is generated in the following way: based on the task information of the current subtask, a target code framework is selected from a preset set of multiple code frameworks, and a target code segment is selected from a preset set of multiple code segments; based on the target code framework and the target code segment, basic code is generated; using an agent, based on the task information of the current subtask, the basic code is adjusted to obtain the code for the current subtask.
[0013] As an example, the code generation task is used to generate distribution network fault monitoring code, which is used to perform at least one of the following: detecting distribution network faults; locating fault locations; isolating the faulty area; distributing power to non-faulty areas; and restoring power supply to the faulty area.
[0014] According to a second aspect of this disclosure, a method for monitoring faults in a power distribution network is provided. The method includes: receiving operational data of the power distribution network; inputting the operational data into pre-generated code to obtain fault monitoring results output from the pre-generated code, wherein the pre-generated code is generated according to the code generation method described in this disclosure; and controlling the power distribution of the power distribution network based on the fault monitoring results.
[0015] According to a third aspect of this disclosure, an electronic device is provided, the electronic device comprising: a processor; and a memory for storing processor-executable instructions, wherein the processor-executable instructions, when executed by the processor, cause the processor to perform a code generation method according to this disclosure.
[0016] According to a fourth aspect of this disclosure, a computer-readable storage medium is provided that, when instructions in the computer-readable storage medium are executed by a processor of an electronic device, enables the electronic device to perform the code generation method according to this disclosure.
[0017] According to a fifth aspect of this disclosure, a computer program product is provided, including computer-executable instructions that, when executed by at least one processor, implement the code generation method according to this disclosure.
[0018] The technical solution provided in this disclosure brings at least the following beneficial effects: Based on the code generation method, power distribution network fault monitoring method, equipment, medium, and products disclosed herein, semantic parsing can be performed on code generation tasks input by users in natural language. Based on the semantics, the task can be decomposed into multiple sub-tasks. For each sub-task, a suitable code generation method can be selected according to its complexity or difficulty, thereby obtaining the code for each sub-task to complete the entire code generation task. In this way, complex tasks can be decomposed, and different code generation methods can be used for different sub-tasks, thus enabling the handling of complex and multi-dimensional code generation tasks, achieving code generation based on task complexity, and improving code generation efficiency.
[0019] It should be understood that the above general description and the following detailed description are exemplary and explanatory only, and are not intended to limit this disclosure. Attached Figure Description
[0020] The accompanying drawings, which are incorporated in and form part of this specification, illustrate embodiments consistent with this disclosure and, together with the description, serve to explain the principles of this disclosure, and are not intended to unduly limit this disclosure.
[0021] Figure 1This is a schematic flowchart of a code generation method according to an exemplary embodiment of the present disclosure.
[0022] Figure 2 This is a schematic block diagram illustrating the overall workflow of a code generation method according to exemplary embodiments of the present disclosure.
[0023] Figure 3 This is a schematic diagram of the task parsing and requirement abstraction module in the code generation method according to an exemplary embodiment of the present disclosure.
[0024] Figure 4 This is a schematic diagram of the task complexity assessment and routing decision module in the code generation method according to an exemplary embodiment of the present disclosure.
[0025] Figure 5 This is a schematic diagram of a pre-compiled code calling module in a code generation method according to an exemplary embodiment of the present disclosure.
[0026] Figure 6 This is an illustrative flowchart of a code generation method based on preference ratings in accordance with exemplary embodiments of the present disclosure.
[0027] Figure 7 This is a schematic diagram of a preference code generation module in a code generation method according to an exemplary embodiment of the present disclosure.
[0028] Figure 8 This is a schematic flowchart of a power distribution network fault monitoring method according to an exemplary embodiment of the present disclosure. Detailed Implementation
[0029] In order to enable those skilled in the art to better understand the technical solutions of this disclosure, the technical solutions in the embodiments of this disclosure will be clearly and completely described below with reference to the accompanying drawings.
[0030] It should be noted that the terms "first," "second," etc., used in the specification, claims, and accompanying drawings of this disclosure are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such data can be interchanged where appropriate so that the embodiments of this disclosure described herein can be implemented in orders other than those illustrated or described herein. The embodiments described in the following exemplary embodiments do not represent all embodiments consistent with this disclosure. Rather, they are merely examples of apparatuses and methods consistent with some aspects of this disclosure as detailed in the appended claims.
[0031] It should be noted that the phrase "at least one of several items" in this disclosure refers to three parallel cases: "any one of the several items", "a combination of any number of the several items", and "all of the several items". For example, "including at least one of A and B" includes the following three parallel cases: (1) including A; (2) including B; (3) including A and B. Another example is "performing at least one of step one and step two", which means the following three parallel cases: (1) performing step one; (2) performing step two; (3) performing both step one and step two.
[0032] As mentioned earlier, traditional code generation solutions often focus on generating code snippets, but lack the ability to coordinate the overall task architecture and strategy logic, making it difficult to cope with complex programming tasks that require multi-module collaboration and strategy selection.
[0033] In this regard, exemplary embodiments of the present disclosure relate to the fields of code generation technology and automatic fault handling technology for distribution networks. Exemplary embodiments of the present disclosure propose a code generation method, a distribution network fault monitoring method, an electronic device, a computer-readable storage medium, and a computer program product, which can solve or at least alleviate the above-mentioned problems.
[0034] In a first aspect of an exemplary embodiment of this disclosure, a code generation method is provided.
[0035] The code generation method according to exemplary embodiments of this disclosure can be applied to code generation scenarios. For example, software can be loaded on a user terminal, allowing the user to input code generation instructions. The user terminal can then generate code for a code generation task by executing the code generation method according to exemplary embodiments of this disclosure. As an example, the code generation task can be used to generate distribution network fault monitoring code. This code can be used to generate fault response plans when a fault occurs in the distribution network, for controlling the power distribution of the distribution network.
[0036] The aforementioned user terminal can be such as a tablet computer, a laptop computer, a digital assistant, a wearable device, etc. However, the implementation scenario of the above method is only an example scenario. The code generation method according to the exemplary embodiment of this disclosure can also be applied to other application scenarios. For example, a user can request code generation from a server via a network on a user terminal (e.g., a mobile phone, a desktop computer, a tablet computer, etc.). The server can complete the request by executing the code generation method according to the exemplary embodiment of this disclosure. Here, the server can be an independent server, a server cluster, a cloud computing platform, or a virtualization center.
[0037] Examples of code generation methods according to embodiments of the present disclosure will now be described with reference to the accompanying drawings. Figure 1As shown, the code generation method may include the following steps: In step S110, in response to receiving a code generation instruction input by the user, the code generation instruction can be semantically parsed.
[0038] Here, the code generation instructions contain code generation tasks described in natural language.
[0039] As an example, a code generation task can be used to generate distribution network fault monitoring code. This code can perform at least one of the following: detecting distribution network faults; locating fault locations; isolating the faulty area; distributing power to non-faulty areas; and restoring power to the faulty area. When a distribution network fault occurs, the distribution network fault monitoring code can locate the fault, isolate the faulty section, and restore power to non-faulty areas, minimizing the scope and duration of power outages and improving power supply reliability. Generating distribution network fault monitoring code aims to enable the entire distribution fault handling process to require little or no human intervention, achieving self-healing of distribution network faults and improving fault monitoring and handling efficiency. However, embodiments of this disclosure are not limited to this; the code generation task can also be a task that generates other types of code.
[0040] Code generation instructions can include task requirements and information described in natural language. For example, users can input text describing the function or requirements of the target code to be generated as code generation instructions. Taking the generation of distribution network fault monitoring code as an example, users can upload documents including process manuals, processing specifications, and basic information of the target distribution network for distribution network fault monitoring.
[0041] Here, since the code generation instructions contain unstructured natural language instructions, in this step S110, the received code generation instructions can be semantically parsed to obtain a structured task representation, realizing intelligent conversion from the user side to the automatic code generation side, so as to facilitate subsequent code generation.
[0042] As an example, such as Figure 2 As shown, in response to the task input in step S21, the task can be parsed and the requirements abstracted in step S22.
[0043] In one example, during the process of parsing the task and abstracting the requirements, the input code generation instructions can be normalized and semantically standardized. For instance, after receiving the raw text instructions, semantic standardization can be performed first to generate a standardized semantic representation, so that the user's intent can be more accurately understood during subsequent code generation.
[0044] As an example, the semantic standardization process can employ existing deep learning-based semantic understanding models to uniformly map input instructions to domain terminology. Semantic standardization can map colloquial and non-standardized natural language to professional domain language. For instance, in a power distribution fault monitoring scenario, "power outage" can be mapped to "power interruption," "find fault point" to "fault location," and "leakage" to "insulation fault," etc.
[0045] Furthermore, during semantic standardization, sentiment polarity labeling and intensity quantization can be performed. Sentiment polarity labeling involves extracting and labeling words with polarized sentiment meanings, while intensity quantification involves quantifying adverbs of degree according to a predefined transformation or mapping relationship. For example, the phrase "very urgent" can be quantified to an urgency level of 0.95. Additionally, this process can identify and label modal verbs and their constraint strengths within instructions. As an example, the aforementioned sentiment polarity labeling and intensity quantization can be performed using algorithms such as TextBlob. TextBlob is a sentiment analysis tool based on pattern matching and a pre-trained dictionary. It is a Python library for processing text data, and its built-in sentiment analyzer is implemented using the Pattern library. This algorithm can automatically quantify the sentiment polarity and intensity of input text.
[0046] Furthermore, in another example, a large model-driven parser can be used to perform multi-dimensional semantic parsing of code generation instructions. For instance, after semantic normalization, the normalized instructions can be fed into a large language model-based parser, which operates simultaneously through a multi-task learning framework to convert the instructions into a standardized, structured representation.
[0047] As an example, the parser described above could be implemented based on the CodeT5 model, a large language model pre-trained specifically for code understanding and generation tasks based on the T5 (Text-to-Text Transfer Transformer) architecture. This algorithm supports various code-related tasks, including code summarization, code generation, defect detection, and code translation, and possesses multi-task learning capabilities.
[0048] In the example where the CodeT5 model is used as the parser driven by the large model mentioned above, the input to the parser can be a semantically normalized natural language instruction (e.g., "create a function that takes two integers as input and returns their maximum value"); the output of the parser can be a structured intermediate representation (e.g., an abstract syntax tree (AST) fragment, a domain-specific language (DSL) format, or a canonical code template of the target programming language, etc.).
[0049] For example, a parser can perform intent parsing, entity extraction, style quantization, constraint extraction, etc. Here, intent parsing can refer to the core objective type of the identification task (such as fault detection, fault location, fault isolation, power restoration, etc.).
[0050] Entity extraction refers to the use of named entity recognition technology to extract key entities such as organizations, people, products, and events. Style quantification refers to the use of sentiment analysis models to transform descriptive requirements (such as "responsible" and "pleasant") into quantifiable behavioral parameters. Constraint extraction refers to the identification and structuring of constraints such as time, resources, and laws.
[0051] As an example, the sentiment analysis model described above can utilize publicly available implementations, such as neulab / personality-bert-base (hosted on Hugging Face Model Hub), a joint sentiment-personality analysis model. This model is trained on standard personality-annotated datasets such as myPersonality and Essays, and can receive natural language input and output predicted values for the five personality dimensions.
[0052] The parser can output structured prompts for use in subsequent large model generation or code tuning. As an example, the parser's output can be in a uniform JSON format, and may include the following core fields: json { "task_id":"A unique identifier for the code generation task", descriptors: ["style tag 1","style tag 2"], "constraints": { "temporal":"time constraint", "resource": "resource constraints" }, "entities": ["Entity 1","Entity 2"] }
[0053] Although examples of semantic parsing have been described above, the embodiments of this disclosure are not limited thereto, and other existing semantic parsing methods can also be used, as long as they can extract the user's requirements for the generated code.
[0054] Figure 3 This demonstrates an example module for performing task parsing and requirement abstraction. For example... Figure 3 The task parsing and requirement abstraction module 300 may include a semantic standardization processing module 310 and a parser 320. The semantic standardization processing module 310 can parse heterogeneous data, understand the semantics based on the parsing results, and generate standardized semantic representations. The parser 320 can deeply understand the standardized semantic representations based on Prompt Engineering and large-scale deep reasoning, thereby generating structured semantic parsing results, such as the JSON format example mentioned above.
[0055] In step S120, the code generation task can be decomposed into multiple subtasks based on the results of semantic parsing.
[0056] In this step, complex, multi-dimensional tasks can be broken down into simple, single-dimensional, or low-dimensional subtasks. Subtasks can be sequentially connected in process to form a code generation task; they can also be functionally complementary to specify different aspects of the overall code generation task. Taking power distribution network fault monitoring as an example, subtasks may include: fault detection tasks for detecting faults; fault location tasks for locating fault positions; fault isolation tasks for isolating the faulty area; and fault recovery tasks for distributing power to non-faulty areas and restoring power to the faulty area. Different tasks require different code functionalities, therefore different generation methods can be used.
[0057] As an example, a hierarchical task topology can be generated based on the results of semantic parsing. Each node in the topology is a subtask, and multiple subtasks together form a code generation task.
[0058] For example, based on structured semantic representation, the Hierarchical Task Network (HTN) planning algorithm can be used as a task decomposition algorithm. Specifically, according to the domain classification, the corresponding task template library can be called, and the code generation task, which is the main objective, can be decomposed into multiple levels of sub-objectives through graph planning algorithms, generating an executable task tree containing task dependencies and time series. Each node in the task tree can represent a subtask, and each node can contain complete execution metadata for the corresponding subtask. The execution metadata includes, but is not limited to, at least one of the following: estimated execution time, current task resource requirements, task execution priority score, dependencies with other tasks, task success criteria, etc. For example, the execution metadata of each subtask can be used as the final executable task representation.
[0059] For example, such as Figure 3 As shown, the task parsing and requirement abstraction module 300 may also include a hierarchical executable task tree generation module 330. The hierarchical executable task tree generation module 330 may use the HTN task decomposition algorithm to generate a hierarchical task tree, so as to parse multiple subtasks with executable task representations from the input code to generate tasks.
[0060] Although an example of task decomposition has been described above, the embodiments of this disclosure are not limited thereto. Other existing task decomposition methods can also be used, as long as the code generation task can be divided into multiple task modules or task requirements / functions, etc.
[0061] The semantic parsing in step S110 and the task decomposition in step S120 above can perform a fully structured, machine-readable analysis of the input task, providing accurate input specifications for subsequent intelligent routing and code generation. The entire process ensures a reliable conversion from fuzzy natural language to precise machine instructions.
[0062] Return to reference Figure 1 In step S130, for each subtask, the code generation method for executing the subtask can be determined according to the task complexity of the subtask, so as to generate the code for the subtask.
[0063] Here, task complexity can represent the difficulty of performing the code generation task.
[0064] Specifically, in this step, the complexity of each subtask can be evaluated, and intelligent routing decisions can be made based on the evaluation results. Figure 4This example demonstrates a module for task complexity assessment and routing decision-making. Here, intelligent routing decision-making refers to determining the optimal processing path for each subtask through multi-dimensional evaluation and intelligent decision-making (e.g., selecting the generation method that best matches or is most suitable for executing the subtask from multiple optional code generation methods). The core function of intelligent routing decision-making is to achieve optimal resource allocation and adaptive selection of processing modes. This improves the overall processing efficiency and reliability of the code generation task.
[0065] In step 130, a structured task representation, such as that provided by an upstream parser, can be received to evaluate the complexity of each subtask. As an example, in task complexity evaluation, the input subtasks can be subjected to multi-dimensional quantization analysis to generate a complexity vector.
[0066] As an example, task complexity can include policy complexity and computational complexity. For instance, a complexity vector can include multiple elements, which may include quantified values of policy complexity, quantified values of computational complexity, and quantified values of environment dependence, as described below.
[0067] Policy complexity can characterize the decision-making levels required to generate code. Specifically, the decision-making levels required for a task can be evaluated using statistical methods. These decision-making levels may include, but are not limited to, the length of the decision chain (single-step / multi-step / complex network) and the degree of uncertainty (deterministic / risky / uncertain). Taking distribution network fault monitoring as an example, the decision-making levels (or decision chains) may include, in sequence, the following: fault detection, section location, determination of isolation capability, selection of backup power path, and execution of switching operations. The degree of uncertainty can be a quantitative representation of the uncertainty of parameters with partial observability. Parameters with partial observability may include, but are not limited to, fault type (e.g., short circuit / grounding), communication delay, distributed power source status, etc. For example, regarding fault type, if the fault type cannot be determined, and some fault types have been excluded from a set of preset fault types, the degree of uncertainty of the fault type can be determined based on the number of fault types that have not been excluded. The larger the number of fault types that have not been excluded, the higher the degree of uncertainty, and vice versa. As an example, different policy chain lengths and degrees of uncertainty can correspond to different quantitative values. The final policy complexity can be obtained by summing these quantitative values.
[0068] As an example, the above statistical method can be the AST-based Structural Entropy method. This method models the abstract syntax tree corresponding to the target code or code generation task as a tree diagram structure. It uses information entropy theory and graph complexity measurement to quantify the control flow nesting depth, number of branches, dependency complexity, etc. required to generate the code, thereby reflecting its "strategy complexity" or "decision level".
[0069] Computational complexity characterizes the computational resources and time required to generate code. Specifically, it can be used to predict and evaluate the computational resources required for a task through historical data or algorithm analysis. This includes, but is not limited to: expected execution time (e.g., short / medium / long duration levels), CPU / GPU resource requirement levels (e.g., levels 1-5), and memory usage estimates (e.g., low / medium / high memory usage levels). As an example, different execution times / resource requirements / memory usage levels can correspond to different quantified values. The final policy complexity can be obtained by summing these quantified values.
[0070] Environment dependency can represent the degree of coupling between the current task and the external environment. Specifically, the degree of coupling between the task and the external environment can be analyzed based on statistical methods. For example, it can be analyzed the number of external application programming interfaces (APIs) that the current task depends on (or needs to call), the real-time requirements of the current task (e.g., batch processing / near real-time / real-time), and the data sources required by the current task (e.g., the number of types of data sources required, the stability requirements of the data sources (e.g., high / medium / low)).
[0071] For example, such as Figure 4 As shown, the task complexity assessment and routing decision-maker 400 may include a task complexity estimator 410, which can predict the resource requirements of each subtask and analyze the degree of external environment dependence of each subtask, thereby determining the task complexity of each subtask (e.g., calculating the complexity vector).
[0072] In step S130, after determining the task complexity of each subtask, the code generation method for executing the corresponding subtask can be determined based on the task complexity, so as to generate the code for that subtask.
[0073] Here, you can choose any one or more preset methods to generate the code for the current subtask. These preset methods may include, for example, generating code based on pre-compiled code; generating code based on the task preferences of the subtask, where the task preferences represent the user's inclination to perform the current subtask; and generating code using an agent for code generation. These generation methods will be described in detail below.
[0074] As an example, for each subtask, the code generation method can be determined as follows: match the current subtask with the pre-compiled code to obtain the matching result; determine the code generation method based on the task complexity of the current subtask and the matching result.
[0075] Here, there can be multiple pre-compiled codes, which may include historical code generated by the code generation method according to the embodiments of this disclosure, and / or code pre-generated in other ways. As an example, as will be described below... Figure 5 As shown in the pre-compiled code calling module, in embodiments of this disclosure, a code knowledge base can be constructed. This code knowledge base can be used to store code generated according to the code generation method of embodiments of this disclosure. For each stored piece of code, basic information about the code (e.g., code function, code format, code interface, etc.) is recorded, and this basic information is pre-semantized. Therefore, in step S130, the current subtask can be compared with historically generated code stored in the code knowledge base. For example, the task description of the current subtask can be compared with the code function of historical code, thereby enabling the reuse of historical code or fine-tuning of historical code to obtain the code for the current subtask, improving code generation efficiency.
[0076] As an example, semantic vectorized retrieval can be used to match the current subtask with pre-compiled code. Here, semantic vectorized retrieval can refer to embedding the task description of the current subtask (such as the structured semantic parsing results mentioned above) into a high-dimensional vector space, performing an approximate nearest neighbor search in the code knowledge base, and returning the top K most relevant code modules and their similarity scores, where K is a positive integer. For example, in semantic vectorized retrieval, based on an architecture such as Transformer, the subtask description and code function documents can be embedded into the same vector space, and the Approximate Nearest Neighbor (ANN) algorithm can be used to complete the similarity search of a massive code base, returning the Top-K candidate modules and their similarity scores (e.g., in the range of 0-1).
[0077] In addition, matching can also be performed through interface compatibility verification. Here, interface compatibility verification refers to checking the input and output interface specifications of the pre-compiled code (such as the top K most relevant code modules mentioned above), verifying the degree of matching between the parameter types and quantities and the current subtask, and assessing the consistency requirements of the execution environment.
[0078] For example, such as Figure 4 As shown, the task complexity estimator and routing decision maker 400 may further include a knowledge base matching checker 420. The knowledge base matching checker 420 can evaluate the degree of matching between pre-compiled code in the existing code knowledge base and the subtask through a dual mechanism of semantic vectorization retrieval and interface compatibility verification. Here, the degree of matching can be represented by a matching score (e.g., the similarity score mentioned above). The knowledge base matching checker 420 can output the top K most relevant code modules as candidate pre-compiled code and output their corresponding matching scores.
[0079] As an example, the steps described above for determining the code generation method based on the task complexity of the current subtask and the matching results may include: in response to the matching results indicating that the current subtask matches at least one of the pre-compiled codes to a degree higher than or equal to a preset degree, generating code for the current subtask based on the pre-compiled codes; in response to the matching results indicating that the current subtask matches all the pre-compiled codes to a degree lower than a preset degree, determining the code generation method based on the strategy complexity and computational complexity.
[0080] Specifically, when the matching degree is high, it can be assumed that there is code in the pre-compiled code that can be used to complete the current subtask; while when the matching degree is low, the task complexity of the subtask can be further judged. If the complexity is not high, the code of the current subtask may still be obtained based on the pre-compiled code whose matching degree does not reach the above-mentioned preset degree.
[0081] Here, the steps to determine the code generation method based on strategy complexity and computational complexity may include, for example: In response to a policy complexity that is less than or equal to a first threshold, generate code for the current subtask based on pre-compiled code; In response to a policy complexity that is higher than a first threshold but lower than or equal to a second threshold, and a computational complexity that is lower than or equal to a third threshold, code is generated based on the task preference of the subtask, where the task preference represents the user's tendency to perform the current subtask. In response to a policy complexity exceeding a second threshold or a computational complexity exceeding a third threshold, the agent used for code generation generates code for the current subtask.
[0082] As mentioned above, task complexity evaluation results can include dimensions such as computational complexity and policy complexity. For example, if the current subtask has a high degree of matching with the pre-compiled code in the code knowledge base (e.g., a matching score or degree of matching) (e.g., exceeding 0.8) and its policy complexity is low (e.g., less than 0.3), it indicates that the task is a common, well-structured, and predictable simple task. In this case, a pre-compiled code call approach can be used to directly invoke highly optimized fixed program modules for execution, achieving efficient and low-latency responses.
[0083] If the current subtask has low computational resource requirements (e.g., computational complexity less than the third threshold (e.g., 0.6)), but the policy logic is complex (e.g., policy complexity greater than the first threshold (e.g., 0.5)), it indicates that the task requires a certain level of reasoning and personalized expression capabilities. In this case, code generation can be chosen based on the subtask's task preferences. For example, a generative model can be used to create customized code with specific styles or behavioral patterns, balancing flexibility and efficiency (this will be described in detail below).
[0084] For other scenarios, such as tasks that don't match pre-compiled code and have high strategy or computational complexity, large-model inference can be used for generation. This means that deep inference and content generation are performed from scratch using large language models, which, while costly, can handle the most complex and open-ended problem scenarios.
[0085] For example, such as Figure 2 As shown, after the task is parsed and the requirements are abstracted, in step S23, the parsed results (such as the task information of each subtask) can be input into the task complexity evaluation and routing decision-maker.
[0086] like Figure 4 As shown, the task complexity assessment and routing decision-maker 400 may further include an optimal routing decision-maker 430. The optimal routing decision-maker 430 can generate final routing instructions based on a multi-factor decision model. As mentioned above, when generating a task execution plan, intelligent routing decisions can be made based on two key indicators: task complexity and the degree of matching with pre-compiled code. This involves selecting the method of code generation and generating and transmitting the final generated instructions. The final generated routing instructions may include, for example, a target processing module identifier, a task priority identifier, resource reservation requirements, timeout and retry policies, and quality requirement standards. This instruction, along with the task data, is encapsulated into a unified message format and can be distributed to the corresponding downstream processing modules. For example, as... Figure 2As shown, based on the task complexity of each subtask, in step S241 the subtask can be assigned to the pre-compiled code calling module, in step S242 the subtask can be assigned to the preferred code generation module, or in step S243 the subtask can be assigned to the large model, so as to generate the code of the subtask in the corresponding manner (which will be described in detail below).
[0087] Return to reference Figure 1 In step S140, code for the code generation task can be generated based on the code generated for each subtask.
[0088] When the code for each subtask is obtained, the code for the final code generation task can be generated by combining the code for these subtasks. For example, the decomposition logic of each subtask can be obtained from the decomposed code generation task, and the code for each subtask can be combined, etc. The embodiments of this disclosure do not impose any particular limitations on this.
[0089] As an example, such as Figure 2 As shown, in step S25, the code units corresponding to all subtasks can be combined into modules according to the task logic and dependencies to obtain a complete executable program.
[0090] Several examples of alternative ways of generating code according to embodiments of this disclosure will now be described.
[0091] As an example, the code generation method for subtasks may include at least one of the following: generating code based on pre-compiled code; generating code according to the task preferences of the subtask, wherein the task preferences represent the user's inclination to perform the current subtask; or generating code using an agent for code generation.
[0092] In one example, generating code based on pre-compiled code may include: selecting target code from multiple pre-compiled codes to execute the current subtask; analyzing the differences between the code functionality of the target code and the task requirements of the current subtask to obtain analysis results; and obtaining the code for the current subtask based on the analysis results and the existing target code.
[0093] Specifically, in response to the analysis results indicating that the difference is lower than or equal to a preset difference level, the existing code of the target is used as the code of the current subtask; in response to the analysis results indicating that the difference is higher than a preset difference level, the local code in the existing code of the target that differs from the task requirements is identified, and the local code is modified according to the task requirements using an intelligent agent, and the modified existing code of the target is used as the code of the current subtask.
[0094] If it is determined that a code generation method based on pre-compiled code is adopted, the target code for executing the current subtask can be selected from multiple pre-compiled codes in the code knowledge base (e.g., the top K candidate pre-compiled codes with the highest matching degree to the current task). Here, the selected target code does not have to be the pre-compiled code with the highest matching degree.
[0095] As an example, target code can be selected as follows: obtain the historical call success rate and execution efficiency metrics of each precompiled code from the code knowledge base; determine the performance weight of each precompiled code based on its historical call success rate and execution efficiency metrics; determine the retrieval score of each precompiled code based on its performance weight and its matching degree with the current subtask; and select the target code to execute the current subtask based on the retrieval scores of each precompiled code in the code knowledge base.
[0096] Here, the historical call success rate represents the success rate of the precompiled code being called in historical tasks, and the execution efficiency index represents the computation time and resource requirements of the precompiled code.
[0097] Specifically, for each pre-compiled code, the code knowledge base can also record the number of times the code is called to complete a task and the user's feedback on whether the corresponding task was successfully executed in each call, thereby enabling the statistics of the success rate of each pre-compiled code.
[0098] In addition, both computation time and resource requirements can be divided into multiple levels or intervals. Different levels or intervals correspond to different quantitative indicators. The quantitative indicators of computation time and resource requirements can be added together to obtain the execution efficiency indicator.
[0099] As an example, in the embodiments of this disclosure, a two-layer retrieval mechanism based on semantic vectorization retrieval and a memory-based weight adjustment mechanism can be employed to ensure accurate location of the target code. Specifically, based on the aforementioned semantic vectorization retrieval, the top K candidate pre-compiled codes with the highest matching degree to the current task can be obtained. For these candidate pre-compiled codes, a memory-based weight adjustment mechanism can be used. The memory-based weight adjustment mechanism can refer to: recording the historical call success rate and execution efficiency indicators of each code module in the code knowledge base, introducing historical performance weights into the retrieval score, and the final retrieval score of the matching between each code module and the current subtask can be expressed as: retrieval score = semantic similarity × performance weight. Here, semantic similarity can be calculated in the aforementioned semantic vectorization retrieval, i.e., the matching degree. In this way, it can be ensured that high-reliability modules are given priority in invocation, forming a positive feedback loop.
[0100] As an example, given the retrieval scores of each candidate precompiled code, the precompiled code with the highest retrieval score can be selected as the target code mentioned above.
[0101] For the target code, the confidence level of the target code can be further determined. If the confidence level meets the preset requirements, the target code can be directly used as the code for the subtask. If the confidence level does not meet the preset requirements, the target code can be dynamically mutated and adapted to obtain the code for the subtask. Here, the confidence level can be determined based on the retrieval score mentioned above (as mentioned above, retrieval score = semantic similarity × performance weight). For example, when the confidence level is higher than the preset value, it can be considered a high-confidence match; when the confidence level is lower than or equal to the preset value, it can be considered a low-confidence match.
[0102] Specifically, for high-confidence matches (e.g., similarity > 0.85), pre-compiled modules can be directly invoked for standard adaptation via parameterized interfaces. For low-confidence matches (e.g., similarity between 0.6 and 0.85), targeted code modification driven by a Large Language Model (LLM) can be initiated. For example, through difference analysis, subtle differences between the task requirements of the current subtask and the module's functionality can be compared. Code mutations can then be performed on the parts requiring adjustment, using a pre-defined dedicated LLM code corresponding to that local difference for local adjustments and functional enhancements. Furthermore, as an example, the mutation process of the target code can preserve or inherit the architectural advantages and performance characteristics of the original target code module.
[0103] In one example, a mutation instruction can be represented as: The following adaptations are made for the module [module ID]: (1) Add [specific function] (2) Adjust the output format to [required format] (3) Keep the core algorithm unchanged.
[0104] For example, such as Figure 5 As shown, the process of determining the precompiled code described above can be implemented through the precompiled code calling module 500. The precompiled code calling module 500 can intelligently search and match the precompiled code to determine the target code for the current subtask. Once the target code is determined, dynamic mutation and adapter analysis can be performed on the target code to determine whether LLM (Local Management Model) needs to be introduced to perform targeted code modification and fine-tuning of local code within the target code. Finally, the fine-tuned local code and other parts of the target code will be combined to obtain the final code module output.
[0105] In this way, intelligent retrieval, accurate adaptation and efficient reuse of code can be achieved for highly matched tasks. In particular, by integrating semantic retrieval, machine learning and code generation technologies, a code reuse system with continuous evolution capabilities has been built.
[0106] In the above method, generating the code for the current subtask based on pre-compiled code can facilitate standardized and consistent code generation. This method can be used for code that requires standardized and stable output and does not require strategic adjustments.
[0107] For example, in distribution network fault monitoring, taking fault detection as a subtask, the distribution fault monitoring system can monitor electrical quantities such as current and voltage in real time through intelligent terminals (such as distribution switch monitoring terminals (FTUs) and wireless terminal units (DTUs)) installed on the distribution lines. When a sudden surge in current (such as a short circuit) or abnormal voltage is detected, a fault is immediately identified, and a fault alarm signal is sent to the main station system. The logic of this fault detection process is simple, and the determination of whether a fault has occurred can be based on existing execution standards. Therefore, for subtasks that serve as fault detection tasks, code can be generated based on code generated for each subtask.
[0108] For example, in distribution network fault monitoring, taking fault isolation as a subtask, after identifying the faulty section, the master station system issues a "trip" command to the switches (circuit breakers, load switches) at both ends of the faulty section to disconnect them. This physically separates the faulty part from the entire power grid, preventing the fault's impact from further expanding, ensuring the safety of other parts of the power grid, and creating conditions for power restoration. This fault isolation process requires a highly standardized processing strategy (e.g., the switch tripping strategy must remain consistent in every fault). Therefore, for subtasks that serve as fault isolation tasks, code can be generated based on code generated for each subtask.
[0109] In another example, generating code based on the task preferences of a subtask may include: identifying the task preferences of the current subtask based on the results of semantic parsing to obtain a preference score; and generating code for the current subtask based on the preference score.
[0110] Here, preference scoring can be a quantitative representation of task preferences. A high preference score indicates the proportion of subjective decisions in the code generated by the current subtask. Subtasks with high scores require subjective decisions to be executed during runtime. For example, in a distribution network fault monitoring system, the system acts as a dispatcher. In some cases, it needs to strictly follow distribution regulations to generate fault handling strategies; in other cases, it needs to generate fault handling strategies subjectively. For instance, based on the dispatcher's style instructions (such as "prioritize the restoration of key users" or "take the fastest solution"), different codes can be generated. For example, for impersonal / general instructions, standard, optimized network reconfiguration code can be generated; for personalized / policy-based instructions, "prioritize the restoration of key users" is quantified into a preference parameter vector in the algorithm (described below), generating biased restoration code, thus reflecting "policy-based" and "preference-based" generation.
[0111] Specifically, task preferences can characterize a user's decision-making preferences regarding the generated code. Task preferences may include, for example, decision priorities and resource allocation preferences. For instance, taking power distribution network fault monitoring as an example, task preferences may include, for example, the priority of restoring power to electricity users within the power distribution network when a fault occurs, such as giving priority to restoring power to public units like hospitals and schools.
[0112] As an example, based on the semantic parsing results of user input commands, sentiment polarity, modality intensity, and intent clarity can be extracted from the parsed semantic features. Furthermore, the depth, branch complexity, and number of decision nodes of the task tree can be parsed from its structural features. In addition, a comprehensive judgment can be made by combining style preference records of similar tasks in historical features.
[0113] Specifically, initial classification can be performed based on a pre-set rule engine. This engine can contain multiple pre-set keywords. When these keywords are present in the semantic parsing results, the current subtask can be directly categorized into a high-subjectivity category (e.g., a pre-set high-preference score). Keywords can include strong modal words such as "must" and "resolutely." For example, taking the aforementioned power distribution network fault monitoring as an example, the user-inputted task description could include "prioritizing the restoration of power to public units." By detecting the keyword "must," a preference score for the current subtask can be generated. After initial classification, a pre-trained lightweight machine learning model can output a preference score with a continuous value of 0-1, thus providing clear and quantifiable style guidance for subsequent code generation that considers task preferences.
[0114] Although the above describes a method for determining preference scores by combining preset rules with a lightweight machine learning model, the embodiments of this disclosure are not limited thereto. The results of semantic parsing can also be directly input into a pre-trained lightweight machine learning model to output preference scores from the model.
[0115] Once the preference score for a subtask is obtained, it can be compared with a preset value, and the code generation method for that subtask can be determined based on the comparison result.
[0116] In one scenario, in response to a preference score greater than or equal to a preset value, such as... Figure 6 As shown, the code for the current subtask can be generated in the following way: In step S610, the task information of the current subtask can be converted into a preference parameter vector.
[0117] Here, the preference parameter vector can be a quantitative representation of the semantics related to task preferences in the task information. The preset value of the preference score can be set according to actual needs, for example, it can be 0.4.
[0118] Since the code to be generated involves many decision-making or subjective judgment functions during the execution of subtasks with preference scores greater than or equal to preset values, the preference parameter vector of the subtask can be determined from multiple dimensions to generate code based on the preference parameter vector.
[0119] Here, the parameter dimensions included in the preference parameter vector can be determined according to the actual application scenario. For example, taking the scenario of distribution network fault monitoring and self-healing as an example, the preference parameter vector can include the control speed dimension, the recovery object priority dimension, and the cost dimension. For example, in a certain fault self-healing, the preference parameter vector can be [control speed: 0.8, recovery object priority: 0.7, cost: 0.6].
[0120] As an example, an agent based on a large language model can be used to analyze the task information of the current subtask and quantify the semantics in the task information to obtain the aforementioned preference parameter vector. The embodiments of this disclosure do not impose any particular limitations on this, as long as the semantics related to task preferences in the task information can be quantified.
[0121] In addition, preference parameter vectors can also be generated in other ways. For example, a quantization rule base can be preset, and the quantization rules in the quantization rule base can preset the values of each dimension in the preference parameter vector corresponding to different semantic features. The agent can extract semantic features from the task information and determine the values of each dimension in the preference parameter vector according to the quantization rules. For example, the quantization rules can be expressed as: "as soon as possible" corresponds to "control speed: 0.6", "immediately" corresponds to "control speed: 0.8", the recovery object "hospital" corresponds to "recovery object priority: 0.7", the recovery object "residential area" corresponds to "recovery object priority: 0.5", etc. In the embodiments of this disclosure, the quantization rules are not particularly limited and can be set according to actual needs.
[0122] In step S620, a target policy template that matches the preference parameter vector can be obtained from a set of preset policy templates based on the current preference parameter vector.
[0123] Here, each of the multiple strategy templates can be labeled with the range of the preference parameter vector corresponding to the strategy objective, and each strategy template can contain prompts related to the range of the corresponding preference parameter vector.
[0124] For example, a pre-defined strategy template knowledge base can be established, covering code strategy templates from multiple domains. During the strategy matching stage, algorithms such as nearest neighbor retrieval can be used to perform a similarity search on the generated preference parameter vector within the strategy space of the strategy template knowledge base. This enables nearest neighbor strategy retrieval based on the preference parameter vector; for instance, the template with the highest similarity can be used as the target strategy template. This allows for the rapid identification of the strategy template most suitable for the current task's preference requirements, effectively supporting targeted code generation.
[0125] As an example, the prompts in the policy template can include guiding words to instruct the agent to generate code. The prompts in the policy template can be set according to actual needs. Below is an example of a policy template for a power distribution fault monitoring scenario: { "template_id":"DG-FHR-PRI-01", "domain":"Smart Distribution Network", "scenario":"Distribution network fault self-healing", "trigger_keywords": ["Prioritize power restoration for key users", "Ensure power supply to hospitals / schools", "Prioritize critical loads"], "preference_vector_schema": { "critical_load_priority": 0.95, / / Recovery priority for critical users (0~1) "restoration_speed": 0.7, / / Restoration speed preference "total_load_restored": 0.6, / / Total load restored (secondary target) "switch_operation_cost": -0.5 / / Switch operation cost (negative indicator) }, "quantified_strategy_rule": { "description":"During the path selection and load distribution phase, key user nodes are assigned high weights (default weight = 5.0), while ordinary user nodes are assigned a weight of 1.0; the optimization objective function is modified to: max Σ(w_i `restored_i`, where `w_i` is the weight of the key user identifier. "weight_mapping": { "critical_user_weight": 5.0, "normal_user_weight": 1.0 } }, "code_skeleton_hint": [ "def priority_based_self_healing(topology, fault_info, load_priority_map):", # Construct a weighted recovery target # Traverse all feasible paths of the communication switches, # Calculate the weighted recovery score for each path, # Select the path with the highest score and generate operation instructions. " return action_sequence, restored_loads" ], "fallback_behavior": "If no key users are affected, the system will revert to the standard minimal switch operation recovery strategy (corresponding to the general template DG-FHR-STD-00)." }
[0126] In step S630, an agent can be used to generate the code for the current subtask based on the preference parameter vector and the target policy template.
[0127] In this step, the preference parameter vector and the target policy template can be input into an agent such as a large language model to generate code for the current subtask.
[0128] In another scenario, in response to a preference score less than a preset value, the code for the current subtask can be generated as follows: based on the task information of the current subtask, a target code framework is selected from multiple preset code frameworks, and a target code segment is selected from multiple preset code segments; based on the target code framework and the target code segment, basic code is generated; using an agent, the basic code is adjusted according to the task information of the current subtask to obtain the code for the current subtask.
[0129] For example, a pre-defined template library of general-purpose code can be provided. This library can store multiple code frames, each representing the logic or execution flow of the code. Each code frame can be labeled with its function or process. Each code frame may include multiple execution nodes, and each execution node can be populated with code segments to complete its function or task. A pre-defined code knowledge base can also be provided, storing multiple code segments, each labeled with its function.
[0130] If the preference score is less than the preset value, a target code framework can be selected based on the task information of the current subtask, and a corresponding target code segment can be selected based on the requirements of each execution node in the target code framework. Thus, by combining the target code framework and the target code segment, basic code can be generated, which can initially achieve the task objective of the current subtask.
[0131] In addition, the task information and basic code of the current subtask can be input into the agent to optimize the basic code, thereby generating code that is more suitable for the current subtask.
[0132] For example, such as Figure 7 As shown, the process of generating code based on task preferences described above can be implemented by the preference code generation module 700. The preference code generation module 700 may include a subject intelligent judge 710, a general code generation module 720, and a preference abstraction and parameterization module 730. The subject intelligent judge 710 can extract task preferences from the semantic parsing results using a decision model based on multi-feature fusion, and can score the task preferences based on a preset rule engine and output a preference score.
[0133] For tasks with different preference scores, a dual-path code generation mechanism can be adopted. For tasks with low preference scores (e.g., scores < 0.4), the general code generation module 720 can select a basic code template or framework from a general template library and inject best practice code snippets based on the algorithm design dictionary of a preset knowledge base to output standardized functional code. In addition, LLM can be used to assist in the optimization of this standardized functional code, realizing the rule mapping from the algorithm logic chain (or code logic chain) to the code, and finally generating and outputting the code. For tasks with high preference scores (e.g., scores ≥ 0.4), the optimization process of preference parameter vectors assisted by LLM can be entered. Specifically, the target policy template obtained by policy matching and the preference parameter vector output by the preference abstraction and parameterization module 730 can be combined into structured prompt words, which are then input into the code big model to generate a code version with task preference style.
[0134] In the aforementioned code generation method, after obtaining the structured task representation generated by the upstream module, the agent's intelligent judgment unit can first conduct a specific analysis of the behavioral style preferences inherent in the task. This process is not used to parse the core functional content of the task, but rather focuses on identifying and quantifying the stylistic intentions and behavioral preferences embedded in the task requirements, making the generated code more suitable for customization. Through unique style quantification technology and policy matching mechanism, execution code with distinct behavioral characteristics can be generated for the agent, significantly improving the interpretability of the agent's behavior and its human-machine adaptability.
[0135] Furthermore, to ensure output quality, style consistency verification and static analysis can be integrated during code generation to ensure that the code meets preference parameter requirements and is free from logical conflicts and performance risks. In addition, throughout the entire process, generation traceability information can be retained, supporting iterative optimization. By establishing an end-to-end mapping relationship between "task-pattern-code," true agent-based preference programming is achieved, representing a significant breakthrough in the field of automatic code generation.
[0136] For example, in distribution network fault monitoring, taking the power restoration subtask as an example, after the faulty section is isolated, the distribution network fault monitoring system needs to find a new power supply path for the non-faulty sections that have lost power due to isolation. Specifically, the power restoration task may include: checking whether there are backup tie switches in the grid to supply power to the non-faulty sections from unaffected lines; calculating the optimal power supply path to ensure that the equipment on the new path is not overloaded and the voltage quality is qualified; and remotely closing the corresponding tie switches to restore power. This power restoration task requires strategic power distribution, such as whether to restore power to more users or prioritize important users; whether to choose the fastest path or the safest path, etc. Therefore, for subtasks as power restoration tasks, code can be generated based on the subtask's task preferences.
[0137] In yet another example, generating code using an agent for code generation may include: generating agent instruction information based on task information of the current subtask; and using the agent to generate code for the current subtask based on the agent instruction information.
[0138] In this generation method, subtasks deemed highly complex or innovative are processed using a large model inference module. The agent used to generate code can be driven by a large language model (LLM), essentially a tool-type agent specifically designed for code generation.
[0139] Here, the task information may include at least one of the following: the role definition of the agent; the task description information of the code generation task; the code format required by the code generation task; and the constraints of the generated code.
[0140] For example, task information may include at least one of the following: role definition (e.g., "serving as an expert in agent behavior planning"), task context (e.g., containing structured JSON data processed upstream), output format specification (e.g., requiring the generation of executable Python code compliant with PEP8 standards), and innovative constraints (e.g., "prioritizing the integration of built-in system APIs to ensure execution efficiency") and other explicit paragraphs.
[0141] This prompting structure can effectively guide the generation of high-quality code from large models that is both functionally complete and system-adaptable, while ensuring that the content generated from the large models meets reliability requirements under specific constraints.
[0142] For example, in distribution network fault monitoring, taking fault location as a subtask, after the main station system receives fault information reported by multiple smart terminals, it analyzes the direction and magnitude of the fault current and combines it with the topology of the power grid to accurately calculate the line section where the fault point is located. Since faults that may occur in the distribution network are complex and may be difficult to predict completely, for the location of such complex faults (e.g., intermittent faults, multi-source information conflicts), the reasoning capabilities of large models can be used for in-depth analysis to generate dedicated location algorithm code.
[0143] Furthermore, in embodiments of this disclosure, such as Figure 2As shown, in step S26, the code quality of the final combined code can be evaluated, and in step S27, the output can be confirmed by means of manual or automatic methods. For example, the combined code of each subtask can be automatically put into a sandbox environment for multi-level verification, including but not limited to static checks (code syntax, security vulnerabilities, style consistency) and dynamic checks (running correctness, resource usage, performance baseline testing).
[0144] Furthermore, according to embodiments of this disclosure, the method may include: storing the generated code from the code generation task in a code knowledge base. In this way, the code generated each time can be used as pre-compiled code for subsequent tasks. Figure 2 As shown, in step S28, the output code can be stored in the code knowledge base.
[0145] Specifically, such as Figure 5 As shown, the pre-compiled code calling module 500 may include a knowledge base update and memory management module 510, which possesses continuous learning and self-evolution capabilities. During operation, the knowledge base update and memory management module 510 can store successfully executed high-quality variant code and its corresponding task descriptions into the knowledge base, and remember code characteristics, such as synchronously updating the feature vectors and performance indicators of related code to accumulate effective experience. Furthermore, the knowledge base update and memory management module 510 can also build a failure case library, recording instances of task matching failures or execution anomalies, automatically locating fault points using a root cause analysis (RCA) model, and extracting a reusable set of "avoidance rules" to prevent the recurrence of similar errors. Through the above methods, the knowledge base update and memory management module 510 can achieve code recording and updating.
[0146] In addition, the knowledge base update and memory management module 510 also supports a self-optimization mechanism for the knowledge base, such as including but not limited to periodically recalculating the vector representation of modules to reflect the latest usage status, automatically cleaning up long-unused or inefficient outdated modules, and clustering and reorganizing modules with similar functions according to actual usage patterns, thereby continuously improving the efficiency of knowledge organization and retrieval accuracy, enabling code generation to have intelligent characteristics that dynamically adapt to environmental changes and continuously improve task processing capabilities.
[0147] The verified code samples and their generation chain information (such as task description, intermediate code version and final output) are fed back to the system knowledge base, which not only expands the scale and coverage of the knowledge base, but more importantly, provides continuously optimized training data for the code intelligent retrieval and mutation module, enabling it to continuously improve the accuracy and efficiency of code adaptation, thereby driving the entire code generation system to achieve performance evolution and autonomous enhancement through repeated iterations.
[0148] Among relevant code generation methods, template matching-based methods can quickly generate code with specific patterns using predefined templates and rules, exhibiting high generation efficiency and determinism. However, these methods lack flexibility, making it difficult to adapt to complex and ever-changing programming needs, and the construction and maintenance costs of template and rule bases are high. Statistical machine learning-based methods can utilize historical code data for training, learning the statistical regularities of code syntax and patterns, and generating relatively standardized code snippets. However, these methods struggle to handle long-range dependencies and complex semantic contexts, resulting in limited functional correctness of the generated code. Large language model-based methods can achieve powerful code generation capabilities through pre-training on massive amounts of code, generating diverse code based on natural language descriptions. However, these methods suffer from poor controllability, unstable output, and poor performance in tasks requiring strategic planning and complex system design.
[0149] To address the aforementioned issues, the code generation method according to embodiments of this disclosure can be based on large model intelligent agent technology, and through the organic integration of task parsing and strategy planning, personalized strategy matching, intelligent code reuse and dynamic adaptation, it can achieve automated and high-quality solutions to complex programming tasks.
[0150] Furthermore, this method can employ a hierarchical task decomposition architecture to transform high-level tasks into a sequence of executable subtasks. By introducing a task preference calculation model and a strategy template library, the consistency of code generation strategies and the controllability of style are ensured. Combined with semantic code retrieval and targeted fine-tuning techniques, the efficiency of code reuse and the adaptability of code generation are significantly improved.
[0151] In a second aspect of exemplary embodiments of this disclosure, a method for monitoring faults in a distribution network is provided, such as... Figure 8 As shown, the power distribution network fault monitoring method may include the following steps: In step S810, the operation data of the power distribution network can be received.
[0152] In step S820, running data can be input into the pre-generated code to obtain the fault monitoring results output from the pre-generated code, wherein the pre-generated code is generated according to the code generation method of the embodiments of this disclosure.
[0153] In step S830, the power distribution of the distribution network can be controlled based on the fault monitoring results.
[0154] As mentioned above, the code generated by the code generation task can be used for distribution network fault monitoring. This code can be used to perform at least one of the following: detect distribution network faults; locate fault locations; isolate the faulty area; distribute power to non-faulty areas; and restore power supply to the faulty area.
[0155] Accordingly, the fault monitoring results output by the code may include at least one of the following: distribution network fault detection results; fault location; fault isolation strategy; power distribution strategy for non-faulty areas; and method for restoring power supply to the faulty area.
[0156] The power distribution network fault handling method according to the exemplary embodiments of this disclosure has the same or similar beneficial effects as the code generation method described above, and will not be repeated here.
[0157] According to a third aspect of the embodiments of the present disclosure, an electronic device is provided, the electronic device comprising: a processor; and a memory for storing processor-executable instructions, wherein the processor-executable instructions, when executed by the processor, cause the processor to perform a code generation method according to embodiments of the present disclosure.
[0158] As an example, an electronic device does not necessarily have to be a single device; it can also be a collection of any means or circuits capable of executing the aforementioned instructions (or instruction sets) individually or in combination. An electronic device can also be part of an integrated control system or system manager, or can be configured to interface with a server, either locally or remotely (e.g., via wireless transmission).
[0159] In electronic devices, processors may include central processing units (CPUs), graphics processing units (GPUs), programmable logic devices, dedicated processor systems, microcontrollers, or microprocessors. By way of example and not limitation, processors may also include analog processors, digital processors, microprocessors, multi-core processors, processor arrays, network processors, etc.
[0160] The processor can execute instructions or code stored in memory, which can also store data. Instructions and data can also be sent and received over a network via a network interface device, which can employ any known transport protocol.
[0161] Memory can be integrated with the processor; for example, RAM or flash memory can be housed within an integrated circuit microprocessor. Alternatively, memory can comprise a separate device, such as an external disk drive, storage array, or other storage device that can be used by any database system. Memory and processor can be operatively coupled, or can communicate with each other, for example, via I / O ports, network connections, etc., enabling the processor to read files stored in the memory.
[0162] In addition, electronic devices may include video displays (such as liquid crystal displays) and user interaction interfaces (such as keyboards, mice, touch input devices, etc.). All components of the electronic device can be interconnected via buses and / or networks.
[0163] In an exemplary embodiment, a computer-readable storage medium may also be provided, which, when executed by a processor of an electronic device, enables the electronic device to perform the code generation method as described in the exemplary embodiment above. The computer-readable storage medium may be, for example, a memory including instructions. Optionally, the computer-readable storage medium may be: a read-only memory (ROM), a random access memory (RAM), a random access programmable read-only memory (PROM), an electrically erasable programmable read-only memory (EEPROM), a dynamic random access memory (DRAM), a static random access memory (SRAM), flash memory, non-volatile memory, a CD-ROM, a CD-R, a CD+R, a CD-RW, a CD+RW, a DVD-ROM, a DVD-R, a DVD+R, a DVD-RW, a DVD+RW, a DVD-RAM, a BD-ROM, a BD-R, or a BD-R... LTH, BD-RE, Blu-ray or optical disc storage, hard disk drive (HDD), solid-state drive (SSD), card storage (such as multimedia cards, secure digital (SD) cards, or ultra-fast digital (XD) cards), magnetic tape, floppy disk, magneto-optical data storage device, optical data storage device, hard disk, solid-state drive, and any other device configured to store a computer program and any associated data, data files, and data structures in a non-transitory manner and to provide the computer program and any associated data, data files, and data structures to a processor or computer so that the processor or computer can execute the computer program. The computer program in the aforementioned computer-readable storage medium can run in an environment deployed in computer devices such as clients, hosts, agent devices, servers, etc. Furthermore, in one example, the computer program and any associated data, data files, and data structures are distributed across a networked computer system, such that the computer program and any associated data, data files, and data structures are stored, accessed, and executed in a distributed manner through one or more processors or computers.
[0164] According to exemplary embodiments of the present disclosure, a computer program product may also be provided, the computer program product including computer-executable instructions that, when executed by at least one processor, implement the code generation method according to exemplary embodiments of the present disclosure.
[0165] Other embodiments of this disclosure will readily occur to those skilled in the art upon consideration of the specification and practice of the invention disclosed herein. This disclosure is intended to cover any variations, uses, or adaptations of this disclosure that follow the general principles of this disclosure and include common knowledge or customary techniques in the art not disclosed herein. The specification and examples are to be considered exemplary only, and the true scope and spirit of this disclosure are indicated by the claims.
[0166] Furthermore, it should be noted that although several examples of each step have been described above with reference to the specific accompanying drawings, it should be understood that the embodiments of this disclosure are not limited to the combinations given in the examples. The steps appearing in different drawings can be combined, and the execution order of each step can be changed. No exhaustive list is provided here.
[0167] It should be understood that this disclosure is not limited to the precise structures described above and shown in the accompanying drawings, and various modifications and changes can be made without departing from its scope. The scope of this disclosure is limited only by the appended claims.
Claims
1. A code generation method, characterized in that, The code generation method includes: In response to receiving a code generation instruction input by a user, the code generation instruction is semantically parsed, wherein the code generation instruction contains a code generation task described in natural language; Based on the results of the semantic parsing, the code generation task is decomposed into multiple sub-tasks; For each subtask, based on the task complexity of the subtask, a code generation method for executing the subtask is determined to generate the code for the subtask, wherein the task complexity represents the difficulty of executing the code generation task; Based on the code generated for each subtask, the code for the code generation task is generated.
2. The code generation method according to claim 1, characterized in that, For each subtask, the code generation method is determined in the following way: Match the current subtask with the pre-compiled code to obtain the matching results; The code generation method is determined based on the task complexity of the current subtask and the matching result.
3. The code generation method according to claim 2, characterized in that, The task complexity includes policy complexity and computational complexity. Policy complexity represents the decision-making levels required to generate the code, and computational complexity represents the computational resources and time required to generate the code. The step of determining the code generation method based on the task complexity of the current subtask and the matching result includes: In response to the matching result indicating that the current subtask matches at least one of the pre-compiled codes to a degree greater than or equal to a preset degree, code for the current subtask is generated based on the pre-compiled code; In response to the matching result indicating that the matching degree between the current subtask and all pre-compiled code is lower than the preset degree, the code generation method is determined based on the strategy complexity and the computational complexity.
4. The code generation method according to claim 3, characterized in that, Determining the code generation method based on the strategy complexity and the computational complexity includes: In response to the strategy complexity being lower than or equal to a first threshold, code for the current subtask is generated based on the pre-compiled code; In response to the strategy complexity being higher than the first threshold and lower than or equal to the second threshold, and the computational complexity being lower than or equal to the third threshold, code is generated based on the task preference of the subtask, wherein the task preference represents the user's tendency to perform the current subtask; In response to the policy complexity being higher than the second threshold or the computational complexity being higher than the third threshold, the code for the current subtask is generated using an agent for generating code.
5. The code generation method according to claim 1, characterized in that, The code generation method includes at least one of the following: Generate code based on pre-compiled code; Code is generated based on the task preferences of the subtask, wherein the task preferences represent the user's inclination to perform the current subtask; Code is generated using an intelligent agent designed to generate code.
6. The code generation method according to claim 5, characterized in that, The code generation based on pre-compiled code includes: Select the target code from multiple pre-compiled codes to execute the current subtask; The differences between the code functionality of the target code and the task requirements of the current subtask are analyzed to obtain the analysis results; In response to the analysis result indicating that the difference is lower than or equal to a preset difference level, the existing code of the target is used as the code of the current subtask. In response to the analysis result indicating that the difference is higher than the preset difference level, the local code in the target existing code that differs from the task requirements is identified. Using an intelligent agent, the local code is modified according to the task requirements, and the modified target existing code is used as the code for the current subtask.
7. The code generation method according to claim 6, characterized in that, Select the target code in the following manner: The historical call success rate and execution efficiency index of each pre-compiled code are obtained from the preset code knowledge base. The historical call success rate represents the success rate of the pre-compiled code being called in historical tasks, and the execution efficiency index represents the computation time and resource requirements of the pre-compiled code. The performance weight of each precompiled code is determined based on its historical call success rate and the execution efficiency metric. The retrieval score of each precompiled code is determined based on its performance weight and its matching degree with the current subtask. Based on the retrieval scores of each pre-compiled code in the code knowledge base, the target code for executing the current subtask is selected.
8. The code generation method according to claim 5, characterized in that, The step of generating code based on the task preferences of subtasks includes: Based on the results of the semantic parsing, the task preference of the current subtask is identified to obtain a preference score, wherein the preference score is a quantitative representation of the task preference; In response to the preference score being greater than or equal to a preset value, the code for the current subtask is generated in the following manner: The task information of the current subtask is transformed into a preference parameter vector, wherein the preference parameter vector is a quantitative representation of the semantics related to task preferences in the task information; Based on the current preference parameter vector, a target strategy template matching the preference parameter vector is obtained from a plurality of preset strategy templates. Each strategy template in the plurality of strategy templates is marked with the range of the preference parameter vector corresponding to the strategy target, and each strategy template contains prompt content related to the range of the corresponding preference parameter vector. Using an intelligent agent, based on the preference parameter vector and the target policy template, the agent generates the code for the current subtask. In response to the preference score being less than the preset value, the code for the current subtask is generated in the following manner: Based on the task information of the current subtask, select the target code framework from multiple preset code frameworks, and select the target code segment from multiple preset code segments; Based on the target code framework and the target code segment, generate basic code; Using an intelligent agent, the basic code is adjusted based on the task information of the current subtask to obtain the code for the current subtask.
9. The code generation method according to claim 1, characterized in that, The code generation task is used to generate distribution network fault monitoring code, which is used to perform at least one of the following: detect distribution network faults; locate fault locations; isolate the area where the fault is located; Methods for distributing power to non-faulty areas and restoring power to faulty areas.
10. A method for monitoring faults in a power distribution network, characterized in that, The power distribution network fault monitoring method includes: Receive operational data from the power distribution network; The running data is input into the pre-generated code to obtain the fault monitoring results output from the pre-generated code, wherein the pre-generated code is generated by the code generation method according to any one of claims 1 to 9; Based on the fault monitoring results, the power distribution of the power distribution network is controlled.
11. An electronic device, characterized in that, The electronic device includes: processor; Memory used to store processor-executable instructions. Wherein, when the processor executes the processor, it causes the processor to execute the code generation method according to any one of claims 1 to 9.
12. A computer-readable storage medium, characterized in that, When the instructions in the computer-readable storage medium are executed by the processor of the electronic device, the electronic device is able to perform the code generation method according to any one of claims 1 to 9.
13. A computer program product comprising computer-executable instructions, characterized in that, When the computer-executable instructions are executed by at least one processor, they implement the code generation method according to any one of claims 1 to 9.
Citation Information
Patent Citations
Code generation task adaptive reasoning method, device and equipment
CN120560664A
Code generation method and device, computer equipment and storage medium
CN120610695A
Cited By
Query response and code generation method and system based on power field document analysis
CN121958316A
Query response and code generation method and system based on power field document parsing
CN121958316B
