Code reuse method and device based on AI drive, equipment and medium
Through the AI-driven code analysis and retrieval engine, the problems of standardization and low retrieval efficiency in traditional code reuse methods are solved, intelligent and efficient code reuse is achieved, and software development efficiency is improved.
Patent Information
- Application Number
- CN202510768281.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-06-10
- Publication Date
- 2025-09-19
AI Technical Summary
Traditional code reuse methods lack standardization, have low retrieval efficiency, and are difficult to maintain and update, making them unable to meet the complex needs of modern software development.
The code is analyzed in multiple dimensions through the AI-driven code analysis module. The code snippets are stored in a code knowledge base with a semantic index structure based on the preset reusability evaluation model. The AI retrieval engine is used for semantic similarity matching, and the best matching code snippets are located through a multi-dimensional retrieval algorithm. Incremental modification and value-tiered management are performed in combination with deep learning models.
It realizes intelligent and efficient code reuse, improves development efficiency, improves the accuracy of code retrieval and maintenance management efficiency, and reduces duplication of work.
Smart Images

Figure CN120669975A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of computer technology, and in particular to an AI-based code reuse method, apparatus, device, and medium. Background Art
[0002] In modern software development, code reuse is an important means to improve development efficiency and reduce duplication of work. However, traditional code reuse methods have many limitations and are unable to meet the increasingly complex needs of software development.
[0003] Traditional code reuse mainly relies on the experience and manual management of developers. Developers usually reuse code snippets previously written by themselves or their team in projects, or look for available code from the open source community. However, this approach has problems such as lack of standardization, low retrieval efficiency, and difficulty in maintenance and updating.
[0004] As the complexity of software development projects continues to increase and the size of development teams continues to expand, traditional code reuse methods can no longer meet the needs of modern software development. Therefore, a more intelligent and efficient code reuse solution is needed to address the limitations of existing methods. Summary of the Invention
[0005] The embodiments of the present invention provide an AI-driven code reuse method, apparatus, device, and medium, which can realize intelligent and efficient code reuse.
[0006] According to one aspect of the present invention, a code reuse method based on AI driving is provided, comprising:
[0007] When a code submission event is detected, the code scanning process is triggered by the webhook listening service configured in the version control system. The AI-driven code analysis module performs multi-dimensional analysis of the submitted code, extracting code language features, functional semantic descriptions, and input and output parameter specifications. It then performs a quantitative assessment based on a preset reusability evaluation model and stores code snippets that meet the reuse standards in a code knowledge base with a semantic index structure.
[0008] The AI search engine uses natural language processing technology to analyze annotation semantics and combines deep learning models to calculate the semantic similarity between the requirement description and the code snippets in the knowledge base, and locates the best matching code snippet through a multi-dimensional search algorithm;
[0009] After code reuse is executed, incremental modifications are made to the reused code snippets and change records are automatically generated;
[0010] The usage data of code snippets is collected through scheduled tasks to generate usage frequency trend forecasts, and the value of the code snippets is stratified based on the Pareto analysis principle.
[0011] Optionally, the execution steps of the code analysis module include:
[0012] Obtain code change sets through the version control system API and apply abstract syntax tree parsing technology to build a structured representation of the code;
[0013] Combined with the pre-trained language model, the semantic feature vector of the code is extracted, and the clustering algorithm is used to identify code units with reuse potential;
[0014] Build a code dependency graph based on graph neural network to quantitatively evaluate the independence indicators of code snippets.
[0015] Optionally, the matching algorithm of the AI search engine includes:
[0016] Build a multimodal index structure that integrates text semantic index, parameter type index, and code structure index;
[0017] Apply contrastive learning model to calculate the semantic similarity score between requirement description and code snippet;
[0018] Implement type system matching for parameter constraints and support compatibility verification of generic parameters and optional parameters.
[0019] Optionally, the feedback processing mechanism of the maintenance management module includes:
[0020] Classify and encode qualitative feedback based on sentiment analysis technology to extract key improvement points;
[0021] Apply reinforcement learning models to generate code optimization suggestions and form A / B testing plans;
[0022] Through knowledge graph technology, feedback issues are associated with code change history to achieve problem tracing.
[0023] Optionally, the method further includes:
[0024] Automatically identify the functional domain of code snippets based on Transformer's zero-shot classification capability;
[0025] Build a hierarchical classification system to support the orthogonal dimensions of business domain classification and technology implementation classification;
[0026] A metaprogramming interface for user-defined classification rules is provided, wherein the metaprogramming interface supports domain-specific classification strategies.
[0027] Optionally, the method further includes:
[0028] Build user profiles based on developers' historical reuse behavior, apply collaborative filtering algorithms to provide personalized code reuse suggestions, and implement user role-based recommendation strategies in cold start scenarios.
[0029] Optionally, the code knowledge base is updated in the following manner:
[0030] Conduct regular code quality inspections and use static code analysis tools to automatically identify potential problems;
[0031] Manage the evolution of code snippets based on a community contribution model;
[0032] The reuse decisions of domain experts are converted into executable rules through knowledge distillation technology.
[0033] According to another aspect of the present invention, there is provided an AI-driven code reuse device, comprising:
[0034] The evaluation unit is used to trigger the code scanning process through the webhook listening service configured in the version control system when a code submission event is detected. The AI-driven code analysis module performs multi-dimensional analysis of the submitted code, extracting code language features, functional semantic descriptions, and input and output parameter specifications. It also performs quantitative evaluation based on a preset reusability evaluation model and stores code snippets that meet the reuse standards in a code knowledge base with a semantic index structure.
[0035] A retrieval unit is used to use an AI retrieval engine to parse annotation semantics based on natural language processing technology and combine it with a deep learning model to calculate the semantic similarity between the requirement description and the code snippets in the knowledge base, and locate the best matching code snippet through a multi-dimensional retrieval algorithm;
[0036] The modification unit is used to make incremental modifications to the reused code snippets and automatically generate change records after the code reuse is executed;
[0037] The prediction unit is used to collect usage data of code snippets through scheduled tasks to generate usage frequency trend predictions, and to perform value stratification on the code snippets based on the Pareto analysis principle.
[0038] According to another aspect of the present invention, an electronic device is provided, comprising:
[0039] At least one processor; and a memory communicatively connected to the at least one processor; wherein the memory stores a computer program executable by the at least one processor, and the computer program is executed by the at least one processor to enable the at least one processor to execute the AI-driven code reuse method described in any embodiment of the present invention.
[0040] According to another aspect of the present invention, a computer-readable storage medium is provided, wherein the computer-readable storage medium stores computer instructions, and the computer instructions are used to enable a processor to implement the AI-driven code reuse method described in any embodiment of the present invention when executed.
[0041] The solution of the embodiment of the present invention provides an efficient and intelligent solution for software development by combining AI technology with code reuse. It has broad application prospects and practical significance and can significantly improve development efficiency.
[0042] It should be understood that the content described in this section is not intended to identify the key or important features of the embodiments of the present invention, nor is it intended to limit the scope of the present invention. Other features of the present invention will become readily understood through the following description. BRIEF DESCRIPTION OF THE DRAWINGS
[0043] In order to more clearly illustrate the embodiments of the present invention or the technical solutions in the prior art, the following briefly introduces the drawings required for use in the embodiments or the description of the prior art. Obviously, the drawings described below are some embodiments of the present invention. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying any creative work.
[0044] Figure 1 This is a flowchart of an AI-driven code reuse method provided by one embodiment of the present invention;
[0045] Figure 2 1 is a schematic structural diagram of an AI-driven code reuse device provided by one embodiment of the present invention;
[0046] Figure 3 3 is a schematic diagram of the structure of an electronic device that implements the AI-driven code reuse method according to an embodiment of the present invention. DETAILED DESCRIPTION
[0047] In order to make the purpose, technical solutions and advantages of the embodiments of the present invention clearer, the technical solutions in the embodiments of the present invention will be clearly and completely described below in conjunction with the drawings in the embodiments of the present invention. Obviously, the described embodiments are part of the embodiments of the present invention, not all the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without making creative work are within the scope of protection of the present invention.
[0048] It should be noted that the terms "first", "second", etc. in the description and claims of the present invention and the above-mentioned drawings are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that the numbers used in this way can be interchanged where appropriate, so that the embodiments of the present invention described herein can be implemented in an order other than those illustrated or described herein. In addition, the terms "including" and "having" and any variations thereof are intended to cover non-exclusive inclusions. For example, a process, method, system, product or device that includes a series of steps or units is not necessarily limited to those steps or units clearly listed, but may include other steps or units that are not clearly listed or inherent to these processes, methods, products or devices.
[0049] like Figure 1 As shown, an embodiment of the present invention provides an AI-driven code reuse method, which may include the following steps:
[0050] S110. When a code submission event is detected, the code scanning process is triggered by the Webhook listening service configured in the version control system. The AI-driven code analysis module performs multi-dimensional analysis on the submitted code, extracts code language features, functional semantic descriptions, and input and output parameter specifications, and performs quantitative evaluation based on the preset reusability evaluation model. Code snippets that meet the reuse standards are stored in a code knowledge base with a semantic index structure.
[0051] When a developer commits code to GitLab, the commit listener module immediately captures the commit event. This feature can be achieved by configuring a webhook service on GitLab. In a GitLab project, go to the project's "Settings" page and find the "Webhooks" option. Add a new webhook and configure its URL to point to the system's code commit receiving interface.
[0052] Select the trigger event type as "Push events" to trigger the webhook when the code is submitted.
[0053] Write code to retrieve relevant code information based on the Push event. For example, in Java, you can use the GitLab API to retrieve the list of commits corresponding to the current Push. By traversing the list, you can obtain multiple diffs corresponding to each commit. Call the GitLab interface to retrieve the entire content of the code file corresponding to the CommitId. Based on the diffs, you can obtain the specific additions, deletions, and modifications to the file content in the current commit.
[0054] Use natural language processing (NLP) and machine learning algorithms to deeply analyze the code. NLP analyzes textual information such as comments and function names within the code to preliminarily determine the functional intent of the code. Machine learning algorithms identify code snippets with potential for reuse based on features such as the code's language structure and logical relationships, and simultaneously extract key information. For example, for a Python function code snippet that implements a string reversal function, key information extracted includes the following: the code language is Python, the function description is "implements a string reversal function," and the input parameter is a string type parameter.
[0055] The extracted code snippets are screened according to the principles of universality, independence, portability, and maintainability. For universality, the application scenarios of the code snippets are analyzed. For example, a universal array search algorithm code snippet is applicable to a variety of data types and business scenarios and has high universality. For independence, the input and output interfaces of the code snippets are checked to ensure that they are poorly coupled with other code snippets. For example, an independent file reading function code snippet only depends on the file path parameter and is independent of other code logic. For portability, the compatibility of the code snippets in different development environments is considered. For example, a code snippet that does not rely on a specific operating system system call has high portability. For maintainability, check whether the code structure is clear and the comments are complete. For example, a code snippet with detailed comments is convenient for subsequent modification and updating. After screening, code snippets that do not meet the requirements are discarded, and code snippets that meet the requirements are saved.
[0056] Receive filtered code snippets and their key information, and create metadata records for each snippet. This metadata includes the snippet's unique identifier, code language, function description, input parameters, submitter information, submission time, and more. This metadata allows developers to easily retrieve and manage code snippets during subsequent development. For example, when implementing a user login verification function, developers can quickly retrieve the relevant code snippet using the keyword "user login verification" in the function description. They can also understand how to use the code snippet based on the input parameters and other information in the metadata, thereby improving development efficiency.
[0057] The code knowledge base is used to store code snippets, classification, and statistical analysis. It includes the following table structure:
[0058] Code snippet table: Stores the core content of a code snippet and related information. Fields include: snippet_id (unique identifier, primary key), code (code content, text type), language (code language, such as Java, Python, etc.), description (functional description, such as "implements string reversal function"), parameters (input parameters, storing function or method input parameter information), usage_count (frequency of use, recording the number of times the code snippet has been reused), created_at (creation time), updated_at (updated time), etc.
[0059] Category table: used to store the category information of code snippets. Fields include: category_id (unique identifier, primary key), category_name (category name, such as "Data Processing" or "User Interaction"), and parent_category_id (parent category identifier, used to build a hierarchical category structure; NULL for top-level categories).
[0060] Code snippet category association table: Establishes a many-to-many association between code snippets and categories. Fields include: snippet_id (foreign key, associated with the code snippet table) and category_id (foreign key, associated with the category table).
[0061] Statistics analysis table: stores usage statistics for code snippets. Fields include: snippet_id foreign key (linking to the code snippet table), usage_date (usage date), usage_count (number of times a snippet is used on that day), etc.
[0062] When code snippets are entered into the knowledge base, AI is required to classify the information. Data in the statistical analysis table can be collected daily using a scheduled task.
[0063] S120. The AI retrieval engine uses natural language processing technology to parse annotation semantics and combines deep learning models to calculate the semantic similarity between the requirement description and the code snippets in the knowledge base, and locates the best matching code snippet through a multi-dimensional retrieval algorithm.
[0064] Define a method to drive retrieval, such as using specific comments during coding to quickly retrieve matching code snippets from the knowledge base. For example, using the comment "@reuse: implements string reversal function" will quickly search the knowledge base based on the keyword "implements string reversal function" in the comment.
[0065] The knowledge base is searched using a large model algorithm. Parameters such as similarity and input matching can be set, and the large model can be trained to ensure the accuracy of the search results.
[0066] When a matching code snippet is retrieved, the code snippet and its related information (such as code language, function description, input parameters, etc.) are displayed to the developer. The developer can decide whether to reuse it in the current development work based on actual needs. When the developer confirms the reuse, the code snippet is added to the current coding area, and information such as the reuse time and number of times is recorded in the knowledge base.
[0067] S130: After the code reuse is executed, incrementally modify the reused code fragment and automatically generate a change record.
[0068] Developers can modify and update reused code snippets to adapt to new requirements or optimize performance. Modified reused code is resubmitted to the repository, updating the original code snippet version and editor information.
[0069] Developers can evaluate reused code snippets. After using a code snippet, they can provide feedback on its effectiveness and any issues encountered. This evaluation feature is available by right-clicking or hovering over a reused method. Evaluations can cover aspects such as the snippet's performance, usability, and compatibility. The system collects this evaluation information and uses it to further optimize and improve the code snippet.
[0070] We use scheduled tasks to analyze the collected evaluation information and, based on developer feedback and suggestions, leverage AI big models to optimize the code snippets in the knowledge base. For example, if a developer reports a performance bottleneck in a code snippet, we use the AI big model to optimize the performance of that code snippet and update the optimized version back to the knowledge base.
[0071] S140. Collect usage data of code snippets through scheduled tasks to generate usage frequency trend predictions, and perform value stratification on the code snippets based on the Pareto analysis principle.
[0072] Periodically collect usage data of code snippets in the knowledge base through scheduled tasks (such as daily / weekly scheduling). The collected data includes:
[0073] Basic usage data: the number of times a code snippet is reused (usage_count), the timestamp of each reuse, caller information, etc.
[0074] Scenario data: business domain label of the reused scenario, calling project name, programming language type, etc.
[0075] Feedback data: Developers’ star ratings for code snippets, performance feedback, problem reports, etc.
[0076] Data collection is achieved through database timing triggers or distributed task scheduling systems to ensure data real-time and integrity.
[0077] Use time series data analysis algorithms (such as ARIMA and Prophet) to model historical usage data and generate usage frequency trend charts by time dimension (week / month / year). For example:
[0078] Identify periodic fluctuations in high-frequency segments (e.g., quarterly business peaks leading to increased reuse of certain types of code);
[0079] Predicting potentially popular segments (based on segments whose usage growth rate exceeds a threshold);
[0080] Analyze usage decay curves to identify code snippets that are gradually becoming deprecated.
[0081] The core logic of Pareto analysis is based on the 80 / 20 principle, which states that 80% of reuse requirements are met by 20% of code snippets. Value stratification is achieved through the following steps: sorting code snippets by their cumulative frequency of use from high to low; calculating the proportion of the frequency of use of the top N snippets to the total number of reuses; identifying key stratification nodes (e.g., the top 20% of snippets contribute 80% of usage), and dividing code snippets into: High-value tier (Top 20%): core code with high frequency reuse and high stability; Medium-value tier (20%-80%): medium reuse frequency, meeting specific scenario requirements; Low-value tier (bottom 20%): snippets with low reuse frequency or compatibility issues.
[0082] Prioritize performance optimization and compatibility maintenance for high-value layer fragments, and allocate more resources for version iteration; add "hot" tags to high-value fragments in search results, sort them by value layer, and improve developer acquisition efficiency; trigger automatic archiving or elimination processes for low-value layer fragments that have not been reused for a long time and have poor feedback, and reduce knowledge base redundancy; use value layering data to guide the priority reuse of high-value fragments when developing new functions, and reduce duplicate development costs.
[0083] In an embodiment of the present invention, the execution steps of the code analysis module include:
[0084] Obtain code change sets through the version control system API and apply abstract syntax tree parsing technology to build a structured representation of the code;
[0085] Combined with the pre-trained language model, the semantic feature vector of the code is extracted, and the clustering algorithm is used to identify code units with reuse potential;
[0086] Build a code dependency graph based on graph neural network to quantitatively evaluate the independence indicators of code snippets.
[0087] The code analysis module retrieves changesets from code commit events by calling the APIs of version control systems (such as GitLab and GitHub). For example, GitLab listens for Push events via a webhook, retrieves the CommitID and corresponding file modification records, and then analyzes the newly added or modified code snippets.
[0088] Use the getDiff interface of the GitLab API to obtain code difference content, and identify the specific location and content of code additions, deletions, and modifications by parsing the Diff text (such as the Unified Diff format).
[0089] For the captured code text, use an AST parser (such as Eclipse JDT for Java or the ast module for Python) to construct a structured syntax tree of the code. The AST converts the code into a hierarchical node structure, where each node represents a syntactic unit (such as a class, function, or expression) in the code, facilitating subsequent semantic analysis. Traversing the AST allows precise location of reusable units such as independent functions and class methods within the code, while excluding irrelevant content such as comments and blank lines.
[0090] Pre-trained language models use pre-trained models for code semantics (such as CodeBERT and GraphCodeBERT) to semantically encode AST nodes or code text. These models are pre-trained on massive code corpora and can capture the functional semantics, variable relationships, and logical structure of the code. Code snippets are converted into token sequences (such as function names, variable names, operators, etc.) and input into the pre-trained model to generate semantic feature vectors, which represent the functional intent of the code (such as "string encryption" and "database connection"). Based on the semantic feature vectors output by the pre-trained model, clustering algorithms (such as K-means and DBSCAN) are used to group code units. The core logic of clustering is to group code snippets with similar semantics (similar functions) into one category and identify code units that appear frequently or have universal value. After clustering, the center vector of each cluster is evaluated, and code units with wide coverage and independent semantics are selected as candidate reuse snippets, such as general tool functions and algorithm modules.
[0091] GNN technology is used to construct a dependency graph of code snippets. The nodes in the graph represent code units (such as functions and classes), and the edges represent dependency relationships (such as function calls and variable references). Dependency relationships can be obtained through AST parsing or static code analysis. For example:
[0092] If function A calls function B, a directed edge from A to B is constructed;
[0093] If class C references variable D, an association edge from C to D is constructed.
[0094] Based on the dependency graph, the independence of code snippets is quantitatively evaluated using the following dimensions:
[0095] Number of dependencies: The number of external units that a code snippet directly depends on. The fewer the number of dependencies, the higher the independence;
[0096] Dependency depth: the maximum length of the dependency chain (e.g., the depth of A→B→C is 2; the lower the depth, the better the portability);
[0097] Coupling degree: The strength of the association between the code snippet and other units (such as call frequency and parameter passing complexity) is calculated through the edge weights of the graph.
[0098] The node embedding technology of graph neural network is used to convert the dependency graph into a numerical vector, and highly independent code snippets are screened out through preset thresholds (such as dependency number ≤3, depth ≤2).
[0099] Based on natural language processing technology, the functional description, comments and other text content of the code snippet are vectorized, allowing the search to break through the keyword matching restrictions and realize synonym replacement search (for example, searching for "string reversal" can match the code snippet of "reversestring").
[0100] Extract parameter type information from code snippets and build a type signature index. Parameter types include primitive types, object types, and generic parameters. You can filter search results by parameter type, for example, filtering for encryption functions with String input parameters.
[0101] The structural features of the code, such as function call chains, control flow structures (loops / conditional statements), are parsed through the abstract syntax tree to generate structured feature vectors (such as AST node sequences) for matching fragments with similar code structures.
[0102] The feature vectors of three types of indexes, namely text semantics, parameter type and code structure, are weightedly fused (e.g. text accounts for 40%, parameters account for 30% and structure accounts for 30%) to form a multi-dimensional retrieval space and improve matching accuracy.
[0103] Using a twin network structure, the semantic vectors of developer annotation requirements and knowledge base code snippets are input into the model, and matching is achieved by comparing the similarity scores between the two.
[0104] A large number of "requirement-code snippet" pairs are used as positive samples and irrelevant pairs as negative samples, and the model parameters are optimized through the contrast loss function.
[0105] Determine the semantic consistency between the requirement description and the code function; filter incompatible fragments based on the technology stack of the project where the code is located, generate a similarity score between 0 and 1 (such as ≥0.7 is considered a high match), and sort the search results by score.
[0106] It supports automatic type conversion and generic parameter matching. For parameters with default values, it allows parameters not mentioned in the requirements to exist, and only verifies the matching degree of required parameters.
[0107] Parse parameter constraints in requirement annotations, extract parameter metadata from code snippets, perform type compatibility checks, and filter out snippets that don't meet the constraints. For example, if a requirement annotation requires "input parameters to be positive numbers," the search will automatically exclude code snippets whose parameter types are strings or that allow negative numbers.
[0108] In an embodiment of the present invention, the feedback processing mechanism of the maintenance management module includes:
[0109] Classify and encode qualitative feedback based on sentiment analysis technology to extract key improvement points;
[0110] Apply reinforcement learning models to generate code optimization suggestions and form A / B testing plans;
[0111] Through knowledge graph technology, feedback issues are associated with code change history to achieve problem tracing.
[0112] The maintenance management module collects qualitative feedback from developers on code snippets through an interactive interface, including natural language comments, star ratings, and problem descriptions. After collection, the text feedback is cleaned and converted into structured data.
[0113] Sentiment analysis models in natural language processing (such as BERT-based sentiment classifiers) are used to determine the sentiment polarity (positive / negative / neutral) of feedback text and identify key improvement points. For example, negative feedback such as "the encryption function takes too long" will be classified as a "performance issue" and the keyword "takes too long" will be extracted; positive feedback such as "clear interface design" will be classified as an "ease of use advantage" and used to optimize recommendation strategies.
[0114] Map feedback to a preset classification system to generate standardized feedback labels.
[0115] The reinforcement learning model is constructed using historical feedback data and change logs from code snippets as training samples. The model's state space includes the current quality metrics of the code snippet and the type of feedback problem; the action space contains possible optimization operations; and the reward function is designed based on the magnitude of improvement in the optimized feedback.
[0116] The optimization suggestion generation process includes: input: feedback classification results (such as "performance bottleneck"), structural features of code snippets (AST nodes), and historical change records; processing: the reinforcement learning model generates the optimal optimization action sequence through the policy network (such as "changing loop traversal to parallel computing") and predicts the effect after optimization; output: generates specific code modification suggestions (with comparison before and after modification) and expected benefits (such as a 20% performance improvement).
[0117] Building an A / B test plan involves generating multiple candidate plans for the optimization suggestions and verifying their effectiveness through the following methods:
[0118] Build a test environment: deploy the original code and the optimized version in the sandbox;
[0119] Simulate call scenarios: Generate test cases based on historical usage data;
[0120] Effect evaluation: Compare the performance indicators, resource usage, etc. of each solution, select the optimal solution and push it to the knowledge base.
[0121] In an embodiment of the present invention, the method further includes:
[0122] Automatically identify the functional domain of code snippets based on Transformer's zero-shot classification capability;
[0123] Build a hierarchical classification system to support the orthogonal dimensions of business domain classification and technology implementation classification;
[0124] Provides a metaprogramming interface for user-defined classification rules, where the metaprogramming interface supports domain-specific classification strategies.
[0125] By using pre-trained Transformer models (such as CodeBERT and T5) to semantically encode code snippets, classification of "unseen categories" can be achieved without annotating training data for specific functional domains. The model understands the mapping relationship between code functions and business logic by learning the general semantic representation of code text. Convert the text content of the code snippet (function name, comments, document strings) into a token sequence; input the pre-trained Transformer model to generate a semantic feature vector; use the text prompting technology to convert the functional domain description into a classification label to achieve semantic matching of the code function. Code snippets are automatically classified into preset functional domains without manual labeling; dynamic expansion of new functional domains is supported. For example, when "blockchain smart contract" related code appears in the knowledge base, the model automatically classifies it through semantic understanding without the need for retraining.
[0126] Business domains are categorized by the business problems the code solves, forming a hierarchical structure that focuses on the code's business semantics. Technical implementations are categorized by the technology stack and implementation approach, focusing on the code's technical attributes. The advantage of orthogonal design is that a single code snippet can belong to multiple business domains and technical categories simultaneously (e.g., an e-commerce order payment function implemented in Java), supporting multi-dimensional retrieval and management.
[0127] A tree-like data structure is used to construct a classification system, where each node contains:
[0128] Category name (such as "Data Processing"), parent node reference (forming a hierarchical relationship), and category description;
[0129] Example of a business domain classification tree: root → enterprise application → customer management → user portrait analysis;
[0130] Example of a technology implementation classification tree: root → back-end technology → database operation → SQL query optimization.
[0131] Through the code snippet classification association table, the code is mapped to the business domain and technical classification nodes at the same time to achieve cross-search.
[0132] The metaprogramming interface provides a programmable classification rule configuration interface, allowing developers to customize classification logic through code or scripts to implement domain-specific classification strategies. The interface supports dynamic loading of user-defined classification functions without modifying the underlying system code.
[0133] Exemplary implementations of domain-specific classification strategies include:
[0134] Rule Example 1: Special classification in the financial sector:
[0135] In financial projects, rules are defined through the metaprogramming interface: "If a code snippet contains the AccountTransaction class and calls the BankAPI, it is automatically classified as financial business → account transaction → real-time settlement."
[0136] Rule Example 2: Technical Classification of AI Algorithms:
[0137] For machine learning projects, define the rule: "If the code uses the TensorFlow framework and contains CNN layer definitions, it is classified as AI technology → deep learning → computer vision."
[0138] Supports code structure matching based on abstract syntax tree; supports text pattern matching; supports combined conditional logic.
[0139] In an embodiment of the present invention, the method further includes: constructing a user profile based on the developer's historical reuse behavior, applying a collaborative filtering algorithm to provide personalized code reuse suggestions, and recommending a strategy based on user roles in a cold start scenario.
[0140] Interactive behaviors include evaluation, collection, and modification records of code snippets; contextual information includes development environment and team collaboration relationships.
[0141] Feature engineering converts behavioral data into numerical feature vectors, for example: functional domain preference vector: records the frequency of reuse by developers in areas such as "data processing" and "security authentication"; technology stack preference vector: records the frequency of using languages such as Java / Python / C++ and frameworks such as Spring / Flink; quality preference vector: reflects developers' preferences for quality indicators such as code complexity and test coverage.
[0142] Incremental learning algorithms are used to update profile features in real time, ensuring that the profile evolves as developer behavior changes. For example, when a developer begins to engage with blockchain projects, the weight of "smart contract"-related features in their technology stack preference vector will dynamically increase.
[0143] Based on the assumption that similar developers may have similar needs, recommendations are generated through the following steps:
[0144] Build a developer-code snippet interaction matrix to record users' code reuse / evaluation behavior;
[0145] Calculate the similarity between the target developer and other developers (such as cosine similarity) to find similar user groups;
[0146] Code snippets that have been reused by similar users but not used by the target developer are selected as recommendation candidates.
[0147] User-based collaborative filtering: For example, developer A and developer B frequently reuse "distributed transaction" related codes. When A starts to develop a new function, the "Seata framework integration" code snippet used by B is recommended.
[0148] Content-based filtering: Combines the semantic features of code snippets with user profiles to recommend code that is similar to the user's historical preferences.
[0149] The high-dimensional interaction matrix is decomposed into a user latent factor matrix and a code latent factor matrix, and the user's potential interest in the code is predicted through matrix multiplication.
[0150] When new developers join or have no historical behavior data, initial recommendations are generated using "user roles" as prior knowledge to avoid "cold start failures" in the recommendation system. Multiple development role labels are pre-set (such as "Java Backend Developer," "Front-end Engineer," "Algorithm Engineer," and "Test Developer"), each associated with a specific technology stack and functional domain preferences.
[0151] When a new user registers, an initial role is assigned based on a questionnaire or team information. Based on the role's preset preference model, frequently reused code snippets are recommended for that role. As user behavior data accumulates, the system gradually transitions from "role recommendations" to "personalized recommendations." If user behavior deviates significantly from the initial role preferences, the system automatically adjusts the role label and updates the recommendation model.
[0152] In an embodiment of the present invention, the code knowledge base is updated in the following manner:
[0153] Conduct regular code quality inspections and use static code analysis tools to automatically identify potential problems;
[0154] Manage the evolution of code snippets based on a community contribution model;
[0155] The reuse decisions of domain experts are converted into executable rules through knowledge distillation technology.
[0156] The knowledge base triggers code quality inspections through scheduled tasks, using static code analysis tools to automatically scan all code snippets, identifying potential issues without running the code. These tools check naming conventions and code formatting; identify logical issues such as null pointer references, unreleased resources, and dead loops; calculate cyclomatic complexity and class coupling to determine code maintainability; and scan for security risks such as SQL injection and code injection.
[0157] Problems discovered during inspections are graded according to their severity, and repair suggestions are automatically generated: for low-risk problems, developers are prompted to make additional improvements; for high-risk problems, an emergency update process is triggered, the AI large model is called to generate a repair plan, and the code submitter or maintainer is notified.
[0158] Build a quantitative model to evaluate developers' contributions to the knowledge base. The indicators include:
[0159] Code quality contribution: the number of times the submitted code snippet is reused, the praise rate, and the defect-free running time;
[0160] Maintenance contribution: number of optimizations to existing code and number of issues fixed;
[0161] Creative Commons Contribution: The completeness and accuracy of the provided functional descriptions and usage examples;
[0162] Community engagement: speed of response to feedback from other developers and number of collaborative optimizations.
[0163] Code snippets or optimization suggestions submitted by developers with high contributions will automatically receive higher review and update priority; user roles are divided according to contribution, such as ordinary developers / core contributors / domain experts, and core contributors can participate in version iteration decisions of code snippets; developers are incentivized to improve code quality through contribution rankings, badge systems, etc. For example, high-frequency and high-quality contributors can obtain knowledge base management permissions.
[0164] Collect the decision-making behaviors of domain experts during code reuse and transform their experience into executable rules or models through knowledge distillation technology: monitor the operation logs of experts when searching, evaluating, and optimizing code; use models such as neural networks to fit expert decision-making patterns and transform complex experience into lightweight rules. Embed the distilled rules into various links of the knowledge base:
[0165] Screening stage: When adding a new code snippet, the reusability is automatically evaluated according to expert rules;
[0166] Search phase: Search results are sorted according to the expert's preferred indicators;
[0167] Maintenance phase: Generate optimization suggestions based on expert experience.
[0168] like Figure 2 As shown, an embodiment of the present invention provides an AI-driven code reuse device, which may include:
[0169] Evaluation unit 210 is configured to trigger a code scanning process via a webhook listening service configured in the version control system when a code submission event is detected. The AI-driven code analysis module performs multi-dimensional analysis of the submitted code, extracts code language features, functional semantic descriptions, and input and output parameter specifications, and performs quantitative evaluation based on a preset reusability evaluation model. Code snippets that meet the reuse criteria are stored in a code knowledge base with a semantic index structure.
[0170] Retrieval unit 220, configured to use an AI retrieval engine to parse annotation semantics based on natural language processing technology and combine with a deep learning model to calculate the semantic similarity between the requirement description and the code snippets in the knowledge base, and locate the best matching code snippet through a multi-dimensional retrieval algorithm;
[0171] A modification unit 230 is used to incrementally modify the reused code snippet and automatically generate a change record after the code reuse is executed;
[0172] The prediction unit 240 is configured to collect usage data of code snippets through a scheduled task to generate a usage frequency trend prediction, and perform value stratification on the code snippets based on the Pareto analysis principle.
[0173] It is understood that the structure illustrated in the embodiment of the present invention does not constitute a specific limitation on the AI-driven code reuse device. In other embodiments of the present invention, the AI-driven code reuse device may include more or fewer components than shown in the figure, or combine certain components, or split certain components, or arrange the components differently. The illustrated components can be implemented in hardware, software, or a combination of software and hardware.
[0174] The information interaction, execution process, etc. between the units in the above-mentioned device are based on the same concept as the embodiment of the method of the present invention. For specific contents, please refer to the description in the embodiment of the method of the present invention and will not be repeated here.
[0175] Figure 3 A schematic diagram of the structure of an electronic device 10 that can be used to implement an embodiment of the present invention is shown. The electronic device is intended to represent various forms of digital computers, such as laptop computers, desktop computers, workstations, personal digital assistants, servers, blade servers, mainframe computers, and other suitable computers. The electronic device can also represent various forms of mobile devices, such as personal digital processing, cellular phones, smart phones, wearable devices (such as helmets, glasses, watches, etc.) and other similar computing devices. The components shown herein, their connections and relationships, and their functions are merely examples and are not intended to limit the implementation of the present invention described and / or claimed herein.
[0176] like Figure 3 As shown, the electronic device 10 includes at least one processor 11 and a memory, such as a read-only memory (ROM) 12, a random access memory (RAM) 13, etc., which is communicatively connected to the at least one processor 11. The memory stores a computer program that can be executed by the at least one processor. The processor 11 can perform various appropriate actions and processes according to the computer program stored in the read-only memory (ROM) 12 or the computer program loaded from the storage unit 18 into the random access memory (RAM) 13. Various programs and data required for the operation of the electronic device 10 can also be stored in the RAM 13. The processor 11, ROM 12, and RAM 13 are connected to each other via a bus 14. An input / output (I / O) interface 15 is also connected to the bus 14.
[0177] Multiple components in the electronic device 10 are connected to the I / O interface 15, including an input unit 16, such as a keyboard, a mouse, etc.; an output unit 17, such as various types of displays, speakers, etc.; a storage unit 18, such as a magnetic disk, an optical disk, etc.; and a communication unit 19, such as a network card, a modem, a wireless communication transceiver, etc. The communication unit 19 allows the electronic device 10 to exchange information / data with other devices via a computer network such as the Internet and / or various telecommunication networks.
[0178] The processor 11 may be any general-purpose and / or specialized processing component with processing and computing capabilities. Some examples of the processor 11 include, but are not limited to, a central processing unit (CPU), a graphics processing unit (GPU), various specialized artificial intelligence (AI) computing chips, various processors that run machine learning model algorithms, a digital signal processor (DSP), and any appropriate processor, controller, microcontroller, etc. The processor 11 executes the various methods and processes described above, such as the AI-driven code reuse method.
[0179] In some embodiments, the AI-driven code reuse method may be implemented as a computer program, which is tangibly contained in a computer-readable storage medium, such as a storage unit 18. In some embodiments, part or all of the computer program may be loaded and / or installed on the electronic device 10 via the ROM 12 and / or the communication unit 19. When the computer program is loaded into the RAM 13 and executed by the processor 11, one or more steps of the AI-driven code reuse method described above may be performed. Alternatively, in other embodiments, the processor 11 may be configured to execute the AI-driven code reuse method in any other appropriate manner (e.g., by means of firmware).
[0180] Various embodiments of the systems and techniques described herein can be implemented in digital electronic circuit systems, integrated circuit systems, field programmable gate arrays (FPGAs), application specific integrated circuits (ASICs), application specific standard products (ASSPs), system-on-chip systems (SOCs), programmable logic devices (CPLDs), computer hardware, firmware, software, and / or combinations thereof. These various embodiments can include being implemented in one or more computer programs that are executable and / or interpreted on a programmable system that includes at least one programmable processor, which can be a special purpose or general purpose programmable processor that can receive data and instructions from a storage system, at least one input device, and at least one output device, and transmit data and instructions to the storage system, the at least one input device, and the at least one output device.
[0181] Computer programs for implementing the methods of the present invention may be written in any combination of one or more programming languages. These computer programs may be provided to a processor of a general-purpose computer, a special-purpose computer, or other programmable data processing device, such that when the computer program is executed by the processor, the functions / operations specified in the flowcharts and / or block diagrams are implemented. The computer program may be executed entirely on the machine, partially on the machine, as a stand-alone software package, partially on the machine and partially on a remote machine, or entirely on a remote machine or server.
[0182] In the context of the present invention, computer-readable storage media can be tangible media that can contain or store a computer program for use with an instruction execution system, device or equipment or used in combination with an instruction execution system, device or equipment. Computer-readable storage media can include but are not limited to electronic, magnetic, optical, electromagnetic, infrared or semiconductor systems, devices or equipment, or any suitable combination of the foregoing. Alternatively, computer-readable storage media can be machine-readable signal media. More specific examples of machine-readable storage media can include electrical connections based on one or more lines, portable computer disks, hard disks, random access memories (RAM), read-only memories (ROM), erasable programmable read-only memories (EPROM or flash memory), optical fibers, portable compact disk read-only memories (CD-ROM), optical storage devices, magnetic storage devices, or any suitable combination of the foregoing.
[0183] To provide interaction with a user, the systems and techniques described herein can be implemented on an electronic device having: a display device (e.g., a CRT (cathode ray tube) or LCD (liquid crystal display) monitor) for displaying information to the user; and a keyboard and pointing device (e.g., a mouse or trackball) through which the user can provide input to the electronic device. Other types of devices can also be used to provide interaction with the user; for example, the feedback provided to the user can be any form of sensory feedback (e.g., visual feedback, auditory feedback, or tactile feedback); and input from the user can be received in any form (including acoustic input, voice input, or tactile input).
[0184] The systems and techniques described herein can be implemented in a computing system that includes back-end components (e.g., as a data server), or a computing system that includes middleware components (e.g., an application server), or a computing system that includes front-end components (e.g., a user computer with a graphical user interface or web browser through which a user can interact with implementations of the systems and techniques described herein), or a computing system that includes any combination of such back-end components, middleware components, or front-end components. The components of the system can be interconnected by any form or medium of digital data communication (e.g., a communication network). Examples of communication networks include: a local area network (LAN), a wide area network (WAN), a blockchain network, and the Internet.
[0185] A computing system may include clients and servers. The clients and servers are typically remote from each other and typically interact via a communication network. This client-server relationship arises through computer programs running on the respective computers, creating a client-server relationship. The server may be a cloud server, also known as a cloud computing server or cloud host. This server is a hosting product within the cloud computing service ecosystem that addresses the management difficulties and limited scalability of traditional physical hosting and VPS services.
[0186] It should be understood that the various forms of the processes shown above can be used to reorder, add, or delete steps. For example, the steps described in the present invention can be performed in parallel, sequentially, or in a different order, as long as the desired results of the technical solution of the present invention can be achieved. This is not limited herein.
[0187] The above specific embodiments do not limit the scope of protection of the present invention. Those skilled in the art will appreciate that various modifications, combinations, sub-combinations, and substitutions may be made based on design requirements and other factors. Any modifications, equivalent substitutions, and improvements made within the spirit and principles of the present invention are intended to be included within the scope of protection of the present invention.
Claims
1. A code reuse method based on AI driving, characterized in that: include: When a code submission event is detected, the code scanning process is triggered by the webhook listening service configured in the version control system. The AI-driven code analysis module performs multi-dimensional analysis of the submitted code, extracting code language features, functional semantic descriptions, and input and output parameter specifications. It then performs a quantitative assessment based on a preset reusability evaluation model and stores code snippets that meet the reuse standards in a code knowledge base with a semantic index structure. The AI search engine uses natural language processing technology to analyze annotation semantics and combines deep learning models to calculate the semantic similarity between the requirement description and the code snippets in the knowledge base, and locates the best matching code snippet through a multi-dimensional search algorithm; After code reuse is executed, incremental modifications are made to the reused code snippets and change records are automatically generated; The usage data of code snippets is collected through scheduled tasks to generate usage frequency trend forecasts, and the value of the code snippets is stratified based on the Pareto analysis principle.
2. The method according to claim 1, characterized in that The execution steps of the code analysis module include: Obtain code change sets through the version control system API and apply abstract syntax tree parsing technology to build a structured representation of the code; Combined with the pre-trained language model, the semantic feature vector of the code is extracted, and the clustering algorithm is used to identify code units with reuse potential; Build a code dependency graph based on graph neural network to quantitatively evaluate the independence indicators of code snippets.
3. The method according to claim 1, characterized in that The matching algorithm of the AI search engine includes: Build a multimodal index structure that integrates text semantic index, parameter type index, and code structure index; Apply contrastive learning model to calculate the semantic similarity score between requirement description and code snippet; Implement type system matching for parameter constraints and support compatibility verification of generic parameters and optional parameters.
4. The method according to claim 1, wherein The feedback processing mechanism of the maintenance management module includes: Classify and encode qualitative feedback based on sentiment analysis technology to extract key improvement points; Apply reinforcement learning models to generate code optimization suggestions and form A / B testing plans; Through knowledge graph technology, feedback issues are associated with code change history to achieve problem tracing.
5. The method according to claim 1, wherein The method further includes: Automatically identify the functional domain of code snippets based on Transformer's zero-shot classification capability; Build a hierarchical classification system to support the orthogonal dimensions of business domain classification and technology implementation classification; A metaprogramming interface for user-defined classification rules is provided, wherein the metaprogramming interface supports domain-specific classification strategies.
6. The method according to claim 1, characterized in that The method further includes: Build user profiles based on developers' historical reuse behavior, apply collaborative filtering algorithms to provide personalized code reuse suggestions, and implement user role-based recommendation strategies in cold start scenarios.
7. The method according to claim 1, characterized in that The code knowledge base is updated in the following ways: Conduct regular code quality inspections and use static code analysis tools to automatically identify potential problems; Manage the evolution of code snippets based on a community contribution model; The reuse decisions of domain experts are converted into executable rules through knowledge distillation technology.
8. A code reuse device based on AI drive, characterized in that: include: The evaluation unit is used to trigger the code scanning process through the webhook listening service configured in the version control system when a code submission event is detected. The AI-driven code analysis module performs multi-dimensional analysis of the submitted code, extracting code language features, functional semantic descriptions, and input and output parameter specifications. It also performs quantitative evaluation based on a preset reusability evaluation model and stores code snippets that meet the reuse standards in a code knowledge base with a semantic index structure. A retrieval unit is used to use an AI retrieval engine to parse annotation semantics based on natural language processing technology and combine it with a deep learning model to calculate the semantic similarity between the requirement description and the code snippets in the knowledge base, and locate the best matching code snippet through a multi-dimensional retrieval algorithm; The modification unit is used to make incremental modifications to the reused code snippets and automatically generate change records after the code reuse is executed; The prediction unit is used to collect usage data of code snippets through scheduled tasks to generate usage frequency trend predictions, and to perform value stratification on the code snippets based on the Pareto analysis principle.
9. An electronic device, characterized in that include: at least one processor; and a memory communicatively connected to the at least one processor; wherein the memory stores a computer program executable by the at least one processor, and the computer program is executed by the at least one processor so that the at least one processor can execute the AI-driven code reuse method according to any one of claims 1 to 7.
10. A computer-readable medium, characterized in that The computer-readable storage medium stores computer instructions, and the computer instructions are used to enable a processor to implement the AI-driven code reuse method according to any one of claims 1 to 7 when executed.
Citation Information
Cited By
Code adoption rate determination method and device, medium, electronic equipment and product
CN121050713A
Code retrieval method and device for AI programming and related equipment
CN121502362A
Code snapshot management method and device and related equipment
CN121704892A