An artificial intelligence assisted programming construction method and system
Patent Information
- Application Number
- CN202611126517.4
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-28
- Publication Date
- 2026-09-01
AI Technical Summary
[0003]然而,现有基于检索增强生成的辅助编程系统存在显著的技术缺陷,其一,检索粒度为纯文本语义匹配,无法捕捉函数调用、类继承、接口实现等结构化依赖关系,当开发者修改某个核心函数时,系统仅能检索到语义相似的代码片段,却无法识别该函数被哪些模块调用、其修改影响哪些下游实体,导致生成的代码缺乏全局结构一致性;其二,跨文件依赖追踪能力严重不足,在大型软件项目中,代码实体的依赖关系往往跨越多个文件和模块,而现有系统采用固定尺寸的文本分块策略,容易切断跨文件的调用链,使得模型获得的上文是不完整或割裂的;其三,现有系统无法支持基于依赖关系的结构化查询,例如查询所有调用了特定函数的方法或查找某个类的全部子类,这类查询在代码审查、影响面分析和重构场景中具有刚性需求;
Smart Images

Figure CN122672777A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of computer technology, specifically to a method and system for constructing programs based on artificial intelligence. Background Technology
[0002] Currently, AI-assisted programming tools based on large language models have been widely used. Existing systems typically employ a retrieval-enhanced generation architecture, which uses code snippets semantically similar to the current problem retrieved from the code repository as references to assist the large language model in completing code generation and completion tasks. This type of method treats code as plain text and relies on vector similarity for snippet matching, which can provide developers with contextual references to a certain extent.
[0003] However, existing retrieval-enhanced generation-based assisted programming systems have significant technical shortcomings. First, the retrieval granularity is based on pure text semantic matching, which cannot capture structured dependencies such as function calls, class inheritance, and interface implementations. When a developer modifies a core function, the system can only retrieve semantically similar code snippets, but cannot identify which modules call the function or which downstream entities are affected by the modification, resulting in a lack of global structural consistency in the generated code. Second, the ability to track cross-file dependencies is severely inadequate. In large software projects, the dependencies of code entities often span multiple files and modules, while existing systems use a fixed-size text chunking strategy, which easily breaks the cross-file call chain, resulting in incomplete or fragmented context obtained by the model. Third, existing systems cannot support structured queries based on dependencies, such as querying all methods that call a specific function or finding all subclasses of a class. Such queries are essential in code review, impact analysis, and refactoring scenarios.
[0004] Therefore, there is an urgent need for an AI-assisted programming method that can perceive and utilize explicit dependencies between codes to overcome problems such as inconsistent code generation structures and difficulties in cross-file tracing caused by the lack of dependency information in existing technologies. Summary of the Invention
[0005] The purpose of this invention is to provide a method and system for constructing software based on artificial intelligence-assisted programming, so as to solve the problems mentioned in the background art.
[0006] To achieve the above objectives, the present invention provides the following technical solution: a method for constructing a program based on artificial intelligence-assisted programming, comprising the following steps:
[0007] S1. Obtain the set of source code files in the target code repository, perform static code analysis, identify code entities and their explicit dependencies, and construct a code dependency graph;
[0008] S2. Receive code assistance request, parse the request, locate the entity where the cursor is located, and match and verify the recognition result with the graph node to obtain the target code entity as the traversal anchor point;
[0009] S3. Using the target code entity as the anchor point, perform forward, reverse and bidirectional dependency traversal in the graph. During traversal, calculate the path weight score based on the dependency type weight and depth decay factor, and filter out the set of directly related entities and the set of indirectly related entities accordingly.
[0010] S4. Obtain the target entity, directly related entities, and indirectly related entities. Add tags according to the dependency relationship type. Keep code snippets for direct entities and only keep signature digests for indirect entities. Attach path descriptions and perform simplification to generate a structure-aware context.
[0011] S5. Merge the structure-aware context and user request according to the thought chain prompt word template, and submit it to the code generation large language model to obtain the target code fragment generated by the model autoregression as the output;
[0012] S6. Perform abstract syntax tree parsing on the generated target code, extract all referenced function and type names, verify their existence and parameter signature consistency in the graph, generate correction prompts and iterate and retry up to three times, and finally return the code that passed the verification and the accompanying warning information.
[0013] Preferably, step S1 specifically includes the following steps:
[0014] S101. After obtaining the set of source code files of the target code repository, perform static code analysis on the set. The abstract syntax tree parser uses a syntax parser to convert each source code file into a tree data structure. By traversing the tree, the code entities of the project skeleton are identified, a unique identifier is created for each entity, and metadata is recorded.
[0015] S102. Control flow analysis, based on the abstract syntax tree, constructs a control flow graph for each method by identifying branches, loops, and return statements. This graph uses basic blocks as nodes and control transfers as edges to represent the execution path sequence. Data flow analysis iteratively solves the arrival-constant equation and active variable equation based on the control flow graph to obtain the definition-use chain of variables and record the propagation path of variables from the assignment point to the read point.
[0016] S103. By traversing the call expression nodes in the abstract syntax tree, the current function is extracted as the caller and the called target is extracted as the callee. The class inheritance relationship and interface implementation relationship are established by reading the names from the parent class child nodes and the interface list child nodes of the class declaration node and matching the corresponding entities. The module import relationship is extracted from the import declaration node and matched with the entity. The data flow dependency relationship is obtained through the variable passing path across function boundaries.
[0017] S104, Treat all entities as nodes All dependent edges as Build a code dependency graph ,in Each edge is represented by a triplet. Storage, in This indicates a dependency on the source node. This indicates a dependency on the target node. The type labels represent types such as call, inheritance, implementation, import, and data flow, and are persistently stored using the Neo4j graph database. Each entity corresponds to a node object and stores complete metadata. Each dependency edge corresponds to a directed relationship and is labeled with its type. Indexes are also created for node names and relationship types.
[0018] Preferably, step S2 specifically includes the following steps:
[0019] S201. Receive a code assistance request from the development end through the application programming interface, and perform code entity identification on the context code fragment carried by the request to extract at least one target code entity;
[0020] S202. When the input is a context code fragment, locate the cursor position, backtrack from that position to the starting position of the nearest function and method definition node, extract the definition scope of the current function, call the syntax parser to perform abstract syntax tree parsing on the code fragment, obtain the local abstract syntax tree structure, and find the innermost syntax node to which the cursor position belongs in the structure.
[0021] S203. If the cursor is on the function call expression node, the name of the called function is read from the name attribute of the node as the target code entity. If the cursor is on the class name node, the class name is read as the target code entity. If the cursor is on the variable reference node, the type name of the variable is read from the type annotation sub-node, and the interface corresponding to the type is used as the target code entity.
[0022] S204. If the cursor position does not belong to any directly identifiable code entity, use a predefined regular expression pattern to scan the range of the line where the cursor is located and the three lines above and below it to extract all matching potential entity names. Verify whether the potential entity name exists in the node set by querying the code dependency graph. Use the existing name as the target code entity and discard the non-existent entity name directly.
[0023] S205. When the input is a natural language query statement, a lightweight named entity recognition model is used to extract entities, predict labels for each word in the query statement, and concatenate all word sequences with labels B-FUNC and I-FUNC into a complete function name, concatenate B-CLASS and I-CLASS into a class name, and concatenate B-MODULE and I-MODULE into a module name.
[0024] S206. After obtaining multiple target code entity names, perform string matching with the node names in the node set. The successfully matched nodes are taken as target code entities. If multiple entities are extracted, the entity closest to the end of the query statement is taken as the primary target, and the rest are retained as auxiliary context.
[0025] Preferably, step S3 specifically includes the following steps:
[0026] S301, with target code entity As the starting anchor point for traversal, in the code dependency graph Perform dependency traversal and read the preset maximum traversal depth. And a dependency type weight mapping table;
[0027] S302, Current depth Initialize to zero for the current node. Query all graphs containing the character "". The set of outgoing edges starting from the origin and with The set of incoming edges ending at the destination ,in , , Indicates the type label, forward traversal along Get target node traversing in reverse order Get source node All nodes obtained at the current depth are deduplicated and then added to the candidate set for the next depth. For each edge traversed, calculate the weight score of that path. ,in , Indicates the number of hops in the path. Indicates the depth decay factor. Indicates the first Dependency type of edge The corresponding numerical weights;
[0028] S303, Traverse to depth Stop when the time is right, and obtain the set of all candidate nodes and their highest path weight scores. ,in , Indicates candidate nodes, This indicates the score of its highest path weight, which will be... Nodes with a shortest distance of 1 are grouped into the directly associated entity set, while those with a distance of 2 to... The nodes are assigned to the indirect related entity set, and an upper limit is set for the indirect entities to be retained. ,in Select the top-ranked entities with the highest weighted scores from the set of indirectly related entities. Each node serves as the final retained indirect related entity, and each retained entity is recorded to... The complete path description.
[0029] Preferably, step S4 specifically includes the following steps:
[0030] S401. Obtain the target code entity, the set of directly associated entities, the set of indirectly associated entities, and the path description recorded for each retained entity. Organize all information in a structured manner according to the dependency relationship type to generate a structure-aware context.
[0031] S402. Read the complete metadata record corresponding to the target code entity from the code dependency graph, and use the record as the target entity header of the context;
[0032] S403. For each entity in the directly associated entity set, read its complete source code fragment and metadata from the graph, and generate the corresponding dependency label text according to the dependency relationship type between the target code entity and the entity.
[0033] S404. Group and arrange all code snippets of directly related entities according to dependency type, and sort them from high to low according to path weight score within the same type.
[0034] Preferably, step S4 further includes the following steps:
[0035] S405. Extract the summary information of entities within the indirectly related entity set, and combine the summary information of each indirect entity with the path description into a concise entry.
[0036] S406. Use a syntax parser to parse each code snippet, access its abstract syntax tree, locate the function and method definition nodes in the tree, extract the name part, parameter list part and return type part of the node, and concatenate them into a line of function signature text, while skipping the entire contents of the function body subtree to keep only the function signature.
[0037] S407. For class definition nodes, after extracting the class name, parent class name and list of implemented interface names, traverse all retained text, remove the comment content marked by various comment symbols, and compress consecutive whitespace characters into a single space character.
[0038] S408. After simplification, all parts are concatenated in the order of target entity header, direct dependent entity group, and indirect dependent entity summary list, and preset separator marks are inserted between each part to finally form structure-aware contextual text.
[0039] S409. Calculate the number of tokens in the context text. If it exceeds the preset context length threshold, remove entries from the indirect entity summary list in ascending order of weight score until the text length is reduced to within the threshold.
[0040] Preferably, step S5 specifically includes the following steps:
[0041] S501. Obtain the structure-aware context and the code generation request of the user's original input, construct the complete input of the large language model according to the preset prompt word template, and fill the metadata about the target code entity in the structure-aware context into the entity description placeholder of the template.
[0042] S502. Fill the signature and code snippet of the entity with the call tag in the directly associated entity collection into the callee placeholder, fill the signature of the entity with the callee tag into the caller placeholder, fill the parent class information corresponding to the inheritance tag into the parent class placeholder, and fill the interface information corresponding to the implementation tag into the interface placeholder.
[0043] S503. For indirectly related entities, the path description and entity signature in their summary information are combined and uniformly filled into the additional context placeholder. The template also contains a code generation task instruction placeholder, which is filled into the position after the user's original input code generation request has been processed by text normalization.
[0044] S504. After completing the filling of all placeholders, submit the constructed prompt text as input to the code generation large language model, and obtain the output as the target code fragment.
[0045] Preferably, step S6 specifically includes the following steps:
[0046] S601. Call the syntax parser to perform abstract syntax tree parsing on the target code fragment, traverse all function call expression nodes and type reference nodes in the tree, and extract the name of each referenced target;
[0047] S602. For each extracted name, perform a string matching query in the node set of the code dependency graph to determine whether the name exists in the graph. If it exists, read the parameter signature and return type of the node from the graph and compare them with the actual parameter type and context expectation type when the node is called in the target code snippet.
[0048] S603. If all referenced names exist in the graph and all type signatures match, the verification passes and the target code snippet is returned to the development end as the final output.
[0049] S604. If a referenced name does not exist in the graph, or exists but the type signature does not match, the verification is deemed to fail. The information of the referenced name or type mismatch and its context position are encapsulated into a correction hint. The correction hint is then concatenated with the original complete hint and submitted as a new input to the code generation language model for the second time. The model is required to rewrite the target code fragment according to the correction hint.
[0050] S605. Repeat the correction process three times. If the verification still fails after three times, return the last generated target code segment along with the verification alarm information to the development end for manual review by the developer.
[0051] The AI-assisted programming construction system includes a graph construction unit, a context generation unit, and a target code output unit.
[0052] The graph construction unit obtains the set of source code files of the target code repository, performs static code analysis, identifies code entities and their explicit dependencies, and constructs a code dependency graph.
[0053] The context generation unit receives code assistance requests, parses the requests, locates the entity where the cursor is located, and matches and verifies the recognition results with the graph nodes to obtain the target code entity as the traversal anchor point. Using the target code entity as the anchor point, it performs forward, reverse, and bidirectional dependency traversals in the graph. During traversal, it calculates the path weight score based on the dependency type weight and depth decay factor, thereby filtering out the set of directly related entities and the set of indirectly related entities. It obtains the target entity, directly related entities, and indirectly related entities, adds labels according to the dependency relationship type, retains code fragments for direct entities, and only retains signature digests for indirect entities, along with path descriptions. After simplification, it generates a structure-aware context.
[0054] The target code output unit integrates the structure-aware context and user request according to the thought chain prompt word template and submits it to the code generation large language model. The target code fragment generated by the model's autoregression is obtained as the output. The generated target code is parsed using an abstract syntax tree to extract all referenced function and type names. The existence and parameter signature consistency of these names are verified in the graph. If the verification fails, a correction prompt is generated and the code is retried up to three times. Finally, the code that passes the verification and the accompanying alarm information are returned.
[0055] Compared with the prior art, the beneficial effects of the present invention are:
[0056] 1. This invention constructs a code dependency graph and replaces traditional plain text vector retrieval with graph traversal, enabling the system to explicitly perceive structured relationships such as function calls, class inheritance, and interface implementations. This overcomes the shortcomings of existing retrieval enhancement generation technologies that rely solely on semantic similarity, resulting in a lack of structural information, and fundamentally solves the problem of inaccurate cross-file dependency tracking.
[0057] 2. This invention employs a hierarchical context construction strategy that retains complete code fragments for directly related entities and only retains signature digests for indirectly related entities. Combined with code simplification, this approach effectively reduces the inference latency and computational cost of large language models by fully preserving key structural information while keeping the context length within a preset threshold.
[0058] 3. This invention incorporates thought chain guidance and dependency relationship tags into the prompt word template, enabling the model to analyze the dependency structure before generating code. This significantly improves the consistency of the generated code with the existing code library in terms of interface specifications and calling conventions. By introducing a dependency consistency verification and iterative correction mechanism, the model output is automatically verified, reducing integration errors caused by non-existent dependencies or type signature mismatches, and improving the reliability and practicality of assisted programming. Attached Figure Description
[0059] Figure 1 An overall method flowchart is provided for embodiments of the present invention. Detailed Implementation
[0060] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0061] Example 1:
[0062] Please see Figure 1This invention provides a technical solution: a method for constructing code based on artificial intelligence-assisted programming, comprising the following steps:
[0063] S1. Obtain the set of source code files in the target code repository, perform static code analysis, identify code entities and their explicit dependencies, and construct a code dependency graph;
[0064] S2. Receive code assistance request, parse the request, locate the entity where the cursor is located, and match and verify the recognition result with the graph node to obtain the target code entity as the traversal anchor point;
[0065] S3. Using the target code entity as the anchor point, perform forward, reverse and bidirectional dependency traversal in the graph. During traversal, calculate the path weight score based on the dependency type weight and depth decay factor, and filter out the set of directly related entities and the set of indirectly related entities accordingly.
[0066] S4. Obtain the target entity, directly related entities, and indirectly related entities. Add tags according to the dependency relationship type. Keep code snippets for direct entities and only keep signature digests for indirect entities. Attach path descriptions and perform simplification to generate a structure-aware context.
[0067] S5. Merge the structure-aware context and user request according to the thought chain prompt word template, and submit it to the code generation large language model to obtain the target code fragment generated by the model autoregression as the output;
[0068] S6. Perform abstract syntax tree parsing on the generated target code, extract all referenced function and type names, verify their existence and parameter signature consistency in the graph, generate correction prompts and iterate and retry up to three times, and finally return the code that passed the verification and the accompanying warning information.
[0069] S1 specifically includes the following steps:
[0070] S101. After obtaining the set of source code files of the target code repository, perform static code analysis on the set. Static code analysis is a series of automated techniques for extracting structured information by parsing source code text. It includes at least abstract syntax tree parsing, control flow analysis, and data flow analysis. Abstract syntax tree parsing uses a syntax parser to convert each source code file into a tree-like data structure. By traversing the tree, the code entities of the project skeleton are identified. The code entities include functions, methods, classes, interfaces, modules, and packages. A unique identifier is created for each entity and metadata is recorded, including name, file path, start and end line numbers, source code fragments, parameter signatures, and return types.
[0071] S102. Control flow analysis, based on the abstract syntax tree, constructs a control flow graph for each method by identifying branches, loops, and return statements. This graph uses basic blocks as nodes and control transfers as edges. A basic block is a continuous sequence of instructions in the source code that does not contain any jump instructions except for the entry and exit points, representing the execution path order. Data flow analysis iteratively solves the arrival-constant equation and active variable equation based on the control flow graph to obtain the definition-use chain of variables and record the propagation path of variables from the assignment point to the read point.
[0072] S103. By traversing the call expression nodes in the abstract syntax tree, the current function is extracted as the caller and the called target is extracted as the callee. The class inheritance relationship and interface implementation relationship are established by reading the names from the parent class child nodes and the interface list child nodes of the class declaration node and matching the corresponding entities. The module import relationship is extracted from the import declaration node and matched with the entity. The data flow dependency relationship is obtained through the variable passing path across function boundaries.
[0073] S104, Treat all entities as nodes All dependent edges as Build a code dependency graph ,in Each edge is represented by a triplet. Storage, in This indicates a dependency on the source node. This indicates a dependency on the target node. The type labels represent types, including calls, inheritance, implementations, imports, and data flows. They are persistently stored using the Neo4j graph database. Each entity corresponds to a node object and stores complete metadata. Each dependency edge corresponds to a directed relationship and is labeled with its type. Indexes are also created for node names and relationship types.
[0074] S2 specifically includes the following steps:
[0075] S201. Receive a code assistance request from the development end through the application programming interface. The code assistance request includes at least the context code at the current code editing position and the natural language code query statement directly entered by the user through the plugin interface. Perform code entity recognition on the context code fragment carried by the request to extract at least one target code entity.
[0076] S202. When the input is a context code fragment, locate the cursor position, backtrack from that position to the starting position of the nearest function and method definition node, extract the definition scope of the current function, call the syntax parser to perform abstract syntax tree parsing on the code fragment, obtain the local abstract syntax tree structure, and find the innermost syntax node to which the cursor position belongs in the structure.
[0077] S203. If the cursor is on the function call expression node, the name of the called function is read from the name attribute of the node as the target code entity. If the cursor is on the class name node, the class name is read as the target code entity. If the cursor is on the variable reference node, the type name of the variable is read from the type annotation sub-node, and the interface corresponding to the type is used as the target code entity.
[0078] S204. If the cursor position does not belong to any directly identifiable code entity, use a predefined regular expression pattern to scan the range of the line where the cursor is located and the three lines above and below it to extract all matching potential entity names. Verify whether the potential entity name exists in the node set by querying the code dependency graph. Use the existing name as the target code entity and discard the non-existent entity name directly.
[0079] S205. When the input is a natural language query, a lightweight named entity recognition model is used for entity extraction. Specifically, the lightweight named entity recognition model is a sequence labeling model obtained by fine-tuning the BERT-base pre-trained language model using a software development domain query corpus labeled with code entity types. It predicts labels for each word in the query statement, concatenates all word sequences labeled B-FUNC and I-FUNC into a complete function name, concatenates B-CLASS and I-CLASS into a class name, and concatenates B-MODULE and I-MODULE into a module name.
[0080] S206. After obtaining multiple target code entity names, perform string matching with the node names in the node set. The successfully matched nodes are taken as target code entities. If multiple entities are extracted, the entity closest to the end of the query statement is taken as the primary target, and the rest are retained as auxiliary context.
[0081] S3 specifically includes the following steps:
[0082] S301, with target code entity As the starting anchor point for traversal, in the code dependency graph Perform dependency traversal and read the preset maximum traversal depth. And a dependency type weight mapping table;
[0083] S302, Current depth Initialize to zero for the current node. Query all graphs containing the character "". The set of outgoing edges starting from the origin and with The set of incoming edges ending at the destination ,in , , Indicates the type label, forward traversal along Get target node traversing in reverse order Get source node All nodes obtained at the current depth are deduplicated and then added to the candidate set for the next depth. For each edge traversed, calculate the weight score of that path. ,in , Indicates the number of hops in the path. Indicates the depth decay factor. Indicates the first Dependency type of edge The corresponding numerical weights;
[0084] S303, Traverse to depth Stop when the time is right, and obtain the set of all candidate nodes and their highest path weight scores. ,in , Indicates candidate nodes, This indicates the score of its highest path weight, which will be... Nodes with a shortest distance of 1 are grouped into the directly associated entity set, while those with a distance of 2 to... The nodes are assigned to the indirect related entity set, and an upper limit is set for the indirect entities to be retained. ,in Select the top-ranked entities with the highest weighted scores from the set of indirectly related entities. Each node serves as the final retained indirect related entity, and each retained entity is recorded to... A complete path description;
[0085] S4 specifically includes the following steps:
[0086] S401. Obtain the target code entity, the set of directly associated entities, the set of indirectly associated entities, and the path description recorded for each retained entity. Organize all information in a structured manner according to the dependency relationship type to generate a structure-aware context.
[0087] S402. Read the complete metadata record corresponding to the target code entity from the code dependency graph, including its name, file path, start and end line numbers, complete source code fragment, parameter signature and return type, and use this record as the target entity header of the context.
[0088] S403. For each entity in the directly associated entity set, read its complete source code fragment and metadata from the graph, and generate corresponding dependency label text according to the dependency relationship type between the target code entity and the entity. If the relationship type is a call relationship and the direction is from the target to the entity, generate a call label. If the direction is opposite, generate a called label. If the relationship type is an inheritance relationship, generate an inheritance label. If the relationship type is an implementation relationship, generate an implementation label. If the relationship type is an import relationship, generate an import label. If the relationship type is a data flow relationship, generate a data flow label.
[0089] S404. Group all code snippets of directly related entities according to dependency type, and sort them from high to low according to path weight score within the same type.
[0090] S4 also includes the following steps:
[0091] S405. Extract the summary information of entities within the indirect related entity set. The summary information includes the entity's name, file path, parameter signature and return type for functions or methods, class name and parent class name for classes, and a complete path description from the target code entity to the entity. Combine the summary information and path description of each indirect entity into a concise entry.
[0092] S406. Use a syntax parser to parse each code snippet, access its abstract syntax tree, locate the function and method definition nodes in the tree, extract the name part, parameter list part and return type part of the node, and concatenate them into a line of function signature text, while skipping the entire contents of the function body subtree to keep only the function signature.
[0093] S407. For class definition nodes, after extracting the class name, parent class name and list of implemented interface names, traverse all retained text, remove the comment content marked by various comment symbols, and compress consecutive whitespace characters into a single space character.
[0094] S408. After simplification, all parts are concatenated in the order of target entity header, direct dependent entity group, and indirect dependent entity summary list, and preset separator marks are inserted between each part to finally form structure-aware contextual text.
[0095] S409. Calculate the number of tokens in the context text. If it exceeds the preset context length threshold, remove entries from the indirect entity summary list in order of weight score from low to high until the text length is reduced to within the threshold.
[0096] S5 specifically includes the following steps:
[0097] S501. Obtain the structure-aware context and the code generation request from the user's original input. Construct the complete input of the large language model according to the preset prompt word template. The prompt word template is designed in the form of a thought chain to guide the model to analyze the dependency relationship before generating the code. Fill the entity description placeholder in the template with the metadata of the target code entity in the structure-aware context, including the name, type and file information of the entity.
[0098] S502. Fill the signature and code snippet of the entity with the call tag in the directly associated entity collection into the callee placeholder, fill the signature of the entity with the callee tag into the caller placeholder, fill the parent class information corresponding to the inheritance tag into the parent class placeholder, and fill the interface information corresponding to the implementation tag into the interface placeholder.
[0099] S503. For indirectly related entities, the path description and entity signature in their summary information are combined and uniformly filled into the additional context placeholder. The template also contains a code generation task instruction placeholder. The original code generation request input by the user is filled into this position after text normalization processing. Text normalization processing includes removing redundant whitespace characters and unifying the punctuation mark format.
[0100] S504. After completing all placeholder filling, the constructed prompt text is submitted as input to the code generation language model. This model is a pre-trained language model based on the Transformer architecture. It receives text sequence input and generates subsequent text sequences as output in an autoregressive manner. The output is then used as the target code fragment.
[0101] S6 specifically includes the following steps:
[0102] S601. Call the syntax parser to perform abstract syntax tree parsing on the target code fragment, traverse all function call expression nodes and type reference nodes in the tree, and extract the name of each referenced target;
[0103] S602. For each extracted name, perform a string matching query in the node set of the code dependency graph to determine whether the name exists in the graph. If it exists, read the parameter signature and return type of the node from the graph and compare them with the actual parameter type and the expected context type when calling the node in the target code snippet. Parameter signature matching is done by comparing whether the type order in the formal parameter list is consistent with the type order in the actual input expression. Return type matching is done by comparing whether the expected context type is compatible with the actual declared return type.
[0104] S603. If all referenced names exist in the graph and all type signatures match, the verification passes and the target code snippet is returned to the development end as the final output.
[0105] S604. If a referenced name does not exist in the graph, or exists but the type signature does not match, the verification is deemed to fail. The referenced name or type mismatch information and its context are encapsulated into a correction prompt, in the format of "Reference to undeclared entity X detected" or "Parameter type when calling X does not match the declaration". The correction prompt is then concatenated with the original complete prompt and submitted as a new input to the code generation language model for the second time. The model is required to rewrite the target code snippet based on the correction prompt.
[0106] S605. Repeat the correction process three times. If the verification still fails after three times, return the last generated target code segment along with the verification alarm information to the development end for manual review by the developer.
[0107] Example 2:
[0108] The present invention also provides an artificial intelligence-assisted programming construction system, including a graph construction unit, a context generation unit, and a target code output unit;
[0109] The graph construction unit obtains the set of source code files of the target code repository, performs static code analysis, identifies code entities and their explicit dependencies, and constructs a code dependency graph.
[0110] The context generation unit receives code assistance requests, parses the requests, locates the entity where the cursor is located, and matches and verifies the recognition results with the graph nodes to obtain the target code entity as the traversal anchor point. Using the target code entity as the anchor point, it performs forward, reverse, and bidirectional dependency traversals in the graph. During traversal, it calculates the path weight score based on the dependency type weight and depth decay factor, and filters out the set of directly related entities and the set of indirectly related entities. It obtains the target entity, directly related entities, and indirectly related entities, adds labels according to the dependency relationship type, retains code fragments for direct entities, and only retains signature digests for indirect entities, along with path descriptions. After simplification, it generates a structure-aware context.
[0111] The target code output unit integrates the structure-aware context and user request according to the thought chain prompt word template and submits it to the code generation large language model. The target code fragment generated by the model's autoregression is obtained as the output. The generated target code is parsed using an abstract syntax tree to extract all referenced function and type names. Their existence and parameter signature consistency are verified in the graph. If the verification fails, a correction prompt is generated and the system iterates and retryes up to three times. Finally, the code that passes the verification and the accompanying alarm information are returned.
[0112] It should be noted that, in this document, relational terms such as "first" and "second" are used only to distinguish one entity or operation from another, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Furthermore, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such process, method, article, or apparatus.
[0113] Although embodiments of the invention have been shown and described, it will be understood by those skilled in the art that various changes, modifications, substitutions and alterations can be made to these embodiments without departing from the principles and spirit of the invention, the scope of which is defined by the appended claims and their equivalents.
Claims
1. A method for constructing code based on artificial intelligence-assisted programming, characterized in that, The method includes the following steps: S1. Obtain the set of source code files in the target code repository, perform static code analysis, identify code entities and their explicit dependencies, and construct a code dependency graph; S2. Receive code assistance request, parse the request, locate the entity where the cursor is located, and match and verify the recognition result with the graph node to obtain the target code entity as the traversal anchor point; S3. Using the target code entity as the anchor point, perform forward, reverse and bidirectional dependency traversal in the graph. During traversal, calculate the path weight score based on the dependency type weight and depth decay factor, and filter out the set of directly related entities and the set of indirectly related entities accordingly. S4. Obtain the target entity, directly related entities, and indirectly related entities. Add tags according to the dependency relationship type. Keep code snippets for direct entities and only keep signature digests for indirect entities. Attach path descriptions and perform simplification to generate a structure-aware context. S5. Merge the structure-aware context and user request according to the thought chain prompt word template, and submit it to the code generation large language model to obtain the target code fragment generated by the model autoregression as the output; S6. Perform abstract syntax tree parsing on the generated target code, extract all referenced function and type names, verify their existence and parameter signature consistency in the graph, generate correction prompts and iterate and retry up to three times, and finally return the code that passed the verification and the accompanying warning information.
2. The method for constructing a program based on artificial intelligence-assisted programming according to claim 1, characterized in that, S1 specifically includes the following steps: S101. After obtaining the set of source code files of the target code repository, perform static code analysis on the set. The abstract syntax tree parser uses a syntax parser to convert each source code file into a tree data structure. By traversing the tree, the code entities of the project skeleton are identified, a unique identifier is created for each entity, and metadata is recorded. S102. Control flow analysis, based on the abstract syntax tree, constructs a control flow graph for each method by identifying branches, loops, and return statements. This graph uses basic blocks as nodes and control transfers as edges to represent the execution path sequence. Data flow analysis iteratively solves the arrival-constant equation and active variable equation based on the control flow graph to obtain the definition-use chain of variables and record the propagation path of variables from the assignment point to the read point. S103. By traversing the call expression nodes in the abstract syntax tree, the current function is extracted as the caller and the called target is extracted as the callee. The class inheritance relationship and interface implementation relationship are established by reading the names from the parent class child nodes and the interface list child nodes of the class declaration node and matching the corresponding entities. The module import relationship is extracted from the import declaration node and matched with the entity. The data flow dependency relationship is obtained through the variable passing path across function boundaries. S104, Treat all entities as nodes All dependent edges as Build a code dependency graph ,in Each edge is represented by a triplet. Storage, in This indicates a dependency on the source node. This indicates a dependency on the target node. The type labels represent types such as call, inheritance, implementation, import, and data flow, and are persistently stored using the Neo4j graph database. Each entity corresponds to a node object and stores complete metadata. Each dependency edge corresponds to a directed relationship and is labeled with its type. Indexes are also created for node names and relationship types.
3. The method for constructing a program based on artificial intelligence-assisted programming according to claim 1, characterized in that, S2 specifically includes the following steps: S201. Receive a code assistance request from the development end through the application programming interface, and perform code entity identification on the context code fragment carried by the request to extract at least one target code entity; S202. When the input is a context code fragment, locate the cursor position, backtrack from that position to the starting position of the nearest function and method definition node, extract the definition scope of the current function, call the syntax parser to perform abstract syntax tree parsing on the code fragment, obtain the local abstract syntax tree structure, and find the innermost syntax node to which the cursor position belongs in the structure. S203. If the cursor is on the function call expression node, the name of the called function is read from the name attribute of the node as the target code entity. If the cursor is on the class name node, the class name is read as the target code entity. If the cursor is on the variable reference node, the type name of the variable is read from the type annotation sub-node, and the interface corresponding to the type is used as the target code entity. S204. If the cursor position does not belong to any directly identifiable code entity, use a predefined regular expression pattern to scan the range of the line where the cursor is located and the three lines above and below it to extract all matching potential entity names. Verify whether the potential entity name exists in the node set by querying the code dependency graph. Use the existing name as the target code entity and discard the non-existent entity name directly. S205. When the input is a natural language query statement, a lightweight named entity recognition model is used to extract entities, predict labels for each word in the query statement, and concatenate all word sequences with labels B-FUNC and I-FUNC into a complete function name, concatenate B-CLASS and I-CLASS into a class name, and concatenate B-MODULE and I-MODULE into a module name. S206. After obtaining multiple target code entity names, perform string matching with the node names in the node set. The successfully matched nodes are taken as target code entities. If multiple entities are extracted, the entity closest to the end of the query statement is taken as the primary target, and the rest are retained as auxiliary context.
4. The method for constructing a program based on artificial intelligence-assisted programming according to claim 1, characterized in that, S3 specifically includes the following steps: S301, with target code entity As the starting anchor point for traversal, in the code dependency graph Perform dependency traversal and read the preset maximum traversal depth. And a dependency type weight mapping table; S302, Current depth Initialize to zero for the current node. Query all graphs containing the character "". The set of outgoing edges starting from the origin and with The set of incoming edges ending at the destination ,in , , Indicates the type label, forward traversal along Get target node traversing in reverse order Get source node All nodes obtained at the current depth are deduplicated and then added to the candidate set for the next depth. For each edge traversed, calculate the weight score of that path. ,in , Indicates the number of hops in the path. Indicates the depth decay factor. Indicates the first Dependency type of edge The corresponding numerical weights; S303, Traverse to depth Stop when the time is right, and obtain the set of all candidate nodes and their highest path weight scores. ,in , Indicates candidate nodes, This indicates the score of its highest path weight, which will be... Nodes with a shortest distance of 1 are grouped into the directly associated entity set, while those with a distance of 2 to... The nodes are assigned to the indirect related entity set, and an upper limit is set for the indirect entities to be retained. ,in Select the top-ranked entities with the highest weighted scores from the set of indirectly related entities. Each node serves as the final retained indirect related entity, and each retained entity is recorded to... The complete path description.
5. The method for constructing a program based on artificial intelligence-assisted programming according to claim 1, characterized in that, S4 specifically includes the following steps: S401. Obtain the target code entity, the set of directly associated entities, the set of indirectly associated entities, and the path description recorded for each retained entity. Organize all information in a structured manner according to the dependency relationship type to generate a structure-aware context. S402. Read the complete metadata record corresponding to the target code entity from the code dependency graph, and use the record as the target entity header of the context; S403. For each entity in the directly associated entity set, read its complete source code fragment and metadata from the graph, and generate the corresponding dependency label text according to the dependency relationship type between the target code entity and the entity. S404. Group and arrange all code snippets of directly related entities according to dependency type, and sort them from high to low according to path weight score within the same type.
6. The method for constructing a program based on artificial intelligence-assisted programming according to claim 5, characterized in that, S4 further includes the following steps: S405. Extract the summary information of entities within the indirectly related entity set, and combine the summary information of each indirect entity with the path description into a concise entry. S406. Use a syntax parser to parse each code snippet, access its abstract syntax tree, locate the function and method definition nodes in the tree, extract the name part, parameter list part and return type part of the node, and concatenate them into a line of function signature text, while skipping the entire contents of the function body subtree to keep only the function signature. S407. For class definition nodes, after extracting the class name, parent class name and list of implemented interface names, traverse all retained text, remove the comment content marked by various comment symbols, and compress consecutive whitespace characters into a single space character. S408. After simplification, all parts are concatenated in the order of target entity header, direct dependent entity group, and indirect dependent entity summary list, and preset separator marks are inserted between each part to finally form structure-aware contextual text. S409. Calculate the number of tokens in the context text. If it exceeds the preset context length threshold, remove entries from the indirect entity summary list in ascending order of weight score until the text length is reduced to within the threshold.
7. The method for constructing a program based on artificial intelligence-assisted programming according to claim 1, characterized in that, S5 specifically includes the following steps: S501. Obtain the structure-aware context and the code generation request of the user's original input, construct the complete input of the large language model according to the preset prompt word template, and fill the metadata about the target code entity in the structure-aware context into the entity description placeholder of the template. S502. Fill the signature and code snippet of the entity with the call tag in the directly associated entity collection into the callee placeholder, fill the signature of the entity with the callee tag into the caller placeholder, fill the parent class information corresponding to the inheritance tag into the parent class placeholder, and fill the interface information corresponding to the implementation tag into the interface placeholder. S503. For indirectly related entities, the path description and entity signature in their summary information are combined and uniformly filled into the additional context placeholder. The template also contains a code generation task instruction placeholder, which is filled into the position after the user's original input code generation request has been processed by text normalization. S504. After completing the filling of all placeholders, submit the constructed prompt text as input to the code generation large language model, and obtain the output as the target code fragment.
8. The method for constructing a program based on artificial intelligence-assisted programming according to claim 1, characterized in that, S6 specifically includes the following steps: S601. Call the syntax parser to perform abstract syntax tree parsing on the target code fragment, traverse all function call expression nodes and type reference nodes in the tree, and extract the name of each referenced target; S602. For each extracted name, perform a string matching query in the node set of the code dependency graph to determine whether the name exists in the graph. If it exists, read the parameter signature and return type of the node from the graph and compare them with the actual parameter type and context expectation type when the node is called in the target code snippet. S603. If all referenced names exist in the graph and all type signatures match, the verification passes and the target code snippet is returned to the development end as the final output. S604. If a referenced name does not exist in the graph, or exists but the type signature does not match, the verification is deemed to fail. The information of the referenced name or type mismatch and its context position are encapsulated into a correction hint. The correction hint is then concatenated with the original complete hint and submitted as a new input to the code generation language model for the second time. The model is required to rewrite the target code fragment according to the correction hint. S605. Repeat the correction process three times. If the verification still fails after three times, return the last generated target code segment along with the verification alarm information to the development end for manual review by the developer.
9. A system for building programming based on artificial intelligence, characterized in that, The programming construction system is applicable to the AI-assisted programming construction method according to any one of claims 1-8, comprising a graph construction unit, a context generation unit, and a target code output unit; The graph construction unit obtains the set of source code files of the target code repository, performs static code analysis, identifies code entities and their explicit dependencies, and constructs a code dependency graph. The context generation unit receives code assistance requests, parses the requests, locates the entity where the cursor is located, and matches and verifies the recognition results with the graph nodes to obtain the target code entity as the traversal anchor point. Using the target code entity as the anchor point, it performs forward, reverse, and bidirectional dependency traversals in the graph. During traversal, it calculates the path weight score based on the dependency type weight and depth decay factor, thereby filtering out the set of directly related entities and the set of indirectly related entities. It obtains the target entity, directly related entities, and indirectly related entities, adds labels according to the dependency relationship type, retains code fragments for direct entities, and only retains signature digests for indirect entities, along with path descriptions. After simplification, it generates a structure-aware context. The target code output unit integrates the structure-aware context and user request according to the thought chain prompt word template and submits it to the code generation large language model. The target code fragment generated by the model's autoregression is obtained as the output. The generated target code is parsed using an abstract syntax tree to extract all referenced function and type names. The existence and parameter signature consistency of these names are verified in the graph. If the verification fails, a correction prompt is generated and the code is retried up to three times. Finally, the code that passes the verification and the accompanying alarm information are returned.