A bidirectional intelligent question-answering code supplement method and system based on a large language model
Two-way intelligent question and answer through a large language model solves the problems of long sequence code fragment errors and lack of semantic understanding caused by existing code completion tools, achieves personalized and customized code completion, and improves development efficiency and code quality.
Patent Information
- Application Number
- CN202410885847.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-07-03
- Publication Date
- 2024-09-13
- Estimated Expiration
- 2044-07-03
AI Technical Summary
Existing code completion tools have errors when generating long sequence code snippets and lack semantic understanding. It is difficult to provide personalized and customized code completion solutions and cannot effectively improve the development experience.
A large language model is used for two-way intelligent question and answer. By entering program module function descriptions and comments, the large language model is used to generate and correct source code and comments to achieve personalized and customized completion of the code, and to ensure the integrity of the code through overall project specification correction. Quality and consistency.
It improves the efficiency and quality of code writing, reduces errors, generates detailed and useful comments, ensures the comprehensiveness and consistency of the code, and is suitable for various software development projects.
Smart Images

Figure CN118426825B
Abstract
Description
Technical Field
[0001] The present invention relates to the field of computer technology, and more specifically, to a two-way intelligent question-answering code supplement method and system based on a large language model. Background Art
[0002] Code completion is a function widely used in modern programming tools. It can help developers quickly enter keywords, methods or functions and omit repetitive work, improve development efficiency, reduce errors, and speed up implementation when writing code. Code completion has become one of the basic tools for programmers. Usually, code completion can automatically complete the code according to the context and relevant language rules. It can also pop up a drop-down list of relevant code snippets or keywords, and provide partial or full names of functions, methods and properties. Common code completion takes the input of entered code and supplements the subsequent code through local input association. For example, entering "stri" automatically associates and supplements the code such as "string". As shown in the attached manual Figure 2 As shown, the picture on the left has a code completion function. After entering "num", code reference examples such as "numpy", "numbers", and "enum" will pop up automatically.
[0003] Some tools based on AI algorithms can complete the code based on program analysis and statistical analysis, and can mainly complete some class names and commonly used code templates. One of the earliest tools released in the field of intelligent code completion in the industry is Kite, which was founded in 2014 and released code intelligent prompt plug-ins in editors such as Atom / Vim / Spyder. In the early stage, it was only for Python developers, and now it has expanded to most mainstream development languages. The JetBrains plug-in was released in early 2020 and the VSCode plug-in was released in early 2021. The main function of the tool Kite is intelligent code completion. From the completion effect, it is not good at generating long sequence code snippets. The longest code generated is usually only two to three words, but its highlight is that it can optimize the overall sorting of the completion results of the IDE. We know that the completion effect of the IDE itself is relatively general. Many of them are simply sorted according to the API name. The slightly better ones will be sorted according to the frequency of use. Kite will combine the context of the code and the needs of the developer to put the API that the developer is more likely to use at the top, thereby reducing the developer's input. However, this method brings limited experience improvement, and the difference with PyCharm's built-in completion is not very big, especially the new version of PyCharm provides sorting optimization based on machine learning. The tool TabNine uses the GPT-2 deep learning model, while Copilot uses the GPT-3 model developed by OpenAI. Based on the GPT-3 model, Copilot obtained the Codex model by learning from GitHub's open source code. This model has powerful code generation capabilities, but because the model is very large and requires sufficient infrastructure support, Copilot can only be tried on a small scale through invitation testing. Alibaba Cloud's intelligent coding plug-in Cosy was released in October 2021. Currently, it only supports Java language and is the tool with the least supported languages. Through Cosy's help document, it is learned that it uses a combination of deep learning models and grammatical analysis to generate long sequence codes through the learning ability of deep learning models, and at the same time, it corrects the errors generated by the model by combining the ability of grammatical analysis. Cosy wants to solve the common problem of generating wrong codes in TabNine, GitHub Copilot, etc. From the user experience, there are indeed fewer error codes, but they still exist. Cosy's code search function extracts commonly used code snippets from GitHub and StackOverflow, allowing developers to easily search for them directly in the IDE.
[0004] The patent "A Character-based Code Completion Method and System" (CN201811223489.3) provides a character-based code completion method and system, including: a source code processing step, using an abstract syntax tree and an identifier tool to parse the source code; a model training step, using an LSTM long short-term memory network model to train a language model; a predictive completion step, completing the code based on the trained language model. The invention takes the code as input, and the completed content lacks semantic understanding and error codes. The invention proposes a restricted character-level recurrent neural network and uses it to complete method calls in the Java language, realizing that in the programming process, not only program sentences can be completed, but also single keywords can be completed. The patent "Code Completion Method, Device and Equipment" (application number CN202210912454.0) includes: obtaining the code context of the code to be completed; constructing a code relationship graph, the code relationship graph includes at least one node corresponding to the code context, the first node corresponding to the code to be completed, and at least one connecting edge, wherein at least one connecting edge includes a first connecting edge between the first node and the second node of at least one node; in the encoding subnetwork, based on the labels of at least one node and the first node, and the label of at least one connecting edge, obtain the graph feature vector of the code relationship graph, wherein the label of at least one node includes the code sequence of the code context, and the labels of the first node and the first connecting edge are preset; in the decoding subnetwork, at least based on the graph feature vector, obtain the code sequence of the code to be completed. This method has a high prediction accuracy. Patent application number CN201811224521.X "A code completion method and system based on dual AST sequences" includes: source code processing step, using abstract syntax tree to parse source code; AST to binary tree step, converting the above abstract syntax tree into two different sequences at the same time; model training step, inputting the two different sequences into LSTM model to train language model; prediction completion step, completing code according to the trained language model. The above patent and other large number of code completion methods consulted all start from the source code, analyze the reference frequency and context association of the source code to complete the code. Summary of the invention
[0005] The technical problem to be solved by the present invention is to provide a method and system for supplementing code based on a large language model for two-way intelligent question and answer. Starting from the application system construction requirements, the program function module description and annotation are used as the starting point, and the large language model is used to perform two-way correction and completion of the annotation and source code. The source code is completed according to the function description and function annotation, and the source code is used to correct and complete the annotation. At the same time, a custom commonly used function module and a coding specification training large model are established to output source code and function modules that meet the enterprise's personalized and customized specifications.
[0006] In order to achieve the above object, the present invention adopts the following technical solutions:
[0007] A method for supplementing code based on a large language model bidirectional intelligent question and answer system comprises the following steps:
[0008] S1: Enter the program module function description and comments, which include the module name, function description, input and output parameter description, key algorithm flow and detailed description of special processing logic, and submit the module function description and comments to the large language model interface after the comments are closed or manually submitted;
[0009] S2: Generate a preliminary module source code result through the large language model interface, the module source code result includes a basic code structure, function definition, parameter processing and preliminary implementation logic, and feed back the generated module source code to the developer for preliminary modification;
[0010] S3: submitting the module source code after preliminary modification to the large language model interface again, and correcting the source code and function annotations according to the feedback results of the large language model interface, wherein the source code and function annotations include error detection, performance optimization suggestions, and evaluation of the rationality of code logic;
[0011] S4: submitting the revised source code and functional annotations to the large language model interface, making unified and standardized revisions to the entire project, and generating module files and engineering project source codes, wherein the module files and engineering project source codes include unified code style, standardized naming rules, standardized annotation formats, and optimized code readability and maintainability;
[0012] S5: Save the revised module file and project source code, and submit them to the large language model interface to generate a final function description and annotation, wherein the final function description and annotation include complete module usage instructions, detailed code annotations, boundary condition processing instructions, and possible exception handling strategies;
[0013] S6: Submitting the module file and the project source code together with the final functional description and annotations to the large language model interface, and making corrections based on the overall project specification suggestions fed back by the large language model interface, the steps comprising:
[0014] S601: Verify the comprehensiveness and consistency of module files and project source code with the final functional description and comments;
[0015] S602: Automatically update code comments to ensure that all comments accurately reflect the source code content;
[0016] S603: Check the dependency between functions and modules to ensure that the calling logic between modules is correct;
[0017] S604: Verify the correctness of cross-module calls to ensure the code consistency and integrity of the entire project.
[0018] Preferably, the functional description and annotations of the program module entered in step S1 specifically include a module name that identifies the program module, a detailed description of the module's functions and intended uses, an input and output parameter description, detailed process steps of key algorithms, and a detailed description of special processing logic. The input and output parameter description includes the parameter name, data type, value range, and meaning. The special processing logic includes error handling, exception handling, and boundary conditions.
[0019] Preferably, the preliminary module source code result generated by the large language model interface in step S2 includes basic code structure, function definition, parameter processing and preliminary implementation logic, wherein the basic code structure specifically includes class definition, interface definition and module division; the function definition specifically includes function name, parameter type and its return value; the parameter processing specifically includes parameter validity check and preprocessing; the preliminary implementation logic specifically includes core algorithm and key steps.
[0020] Preferably, the unified and standardized revision of the entire project in step S4 includes the unification of code style, the standardization of naming rules, the standardization of comment formats, and the optimization of code readability and maintainability; the unification of code style is to use a unified code style guide and formatting tool to automatically format the code; the standardization of naming rules is to adopt consistent naming rules; the standardization of comment formats adopts a unified comment format and document string standard; the optimization of code readability and maintainability is to review and optimize the code through code review and refactoring tools.
[0021] Preferably, the process of correcting the source code and function annotations according to the feedback results of the large language model in step S3 includes error detection, performance optimization suggestions and evaluation of the logic rationality of the code; the error detection is to use the error detection suggestions provided by the static analysis tool and the large language model to automatically detect syntax errors, type errors, undefined variables, and unused variables in the source code; the performance optimization suggestions are to identify performance bottlenecks in the code and provide specific optimization suggestions based on the feedback of the large language model and the performance analysis tool; the evaluation of the logic rationality of the code is to evaluate the logic rationality of the code through the logic check provided by the logic analysis tool and the large language model, ensure that the code execution path is correct, and avoid logic loopholes.
[0022] Preferably, the final functional description and annotations generated in step S5 include complete module usage instructions, detailed code annotations, boundary condition processing instructions and possible exception handling strategies; the complete module usage instructions describe the overall function and usage of the module, including how to initialize the module, call the main functions of the module, and the input and output of the module; the detailed code annotations add detailed annotations to each function and key code segment, explaining its purpose, input parameters, return value and execution logic; the boundary condition processing instructions describe in detail the processing logic of the module under different boundary conditions; the possible exception handling strategy describes the processing strategy of the module when encountering an abnormal situation, including specific exception types, exception capture and processing methods.
[0023] Preferably, ensuring the comprehensiveness and consistency of the project source code and comments in step S6 includes automatic updating of code comments, checking of dependencies between functions and modules, and verification of correctness of cross-module calls; the automatic updating of code comments is to automatically generate and update code comments using a comment generation tool to ensure that the comment content is synchronized with the source code; the checking of dependencies between functions and modules is to use a static code analysis tool to check the dependencies between functions and modules to ensure that all dependencies are correct and no circular dependencies occur; the correctness verification of cross-module calls is to verify the correctness of cross-module calls through unit testing and integration testing frameworks to ensure that the calling logic between modules is correct and error-free.
[0024] The present invention also discloses a two-way intelligent question-answer code supplement system based on a large language model, comprising:
[0025] A source code processing module is used to parse the program module function description and comments, and submit the module function description and comments to the large language model interface after the comments are closed or manually submitted, including a syntax parsing unit, which is used to perform syntax analysis on the program module function description and comments, extract key information, and format and submit it to the large language model interface;
[0026] A code generation module, connected to the large language model interface, for generating a preliminary module source code result; the code generation module includes a code template library for storing commonly used code templates so that the large language model interface can reference them when generating the preliminary module source code, thereby improving the quality and consistency of the generated code;
[0027] A correction module, used to submit the module source code after preliminary modification to the large language model interface again, and to correct the source code and function annotations according to the feedback result of the large language model interface;
[0028] An overall project processing module, used to submit the revised module source code and function annotations to the large language model interface, and to perform unified and standardized revisions on the overall project;
[0029] A storage module, used to save the revised module files and engineering project source code, and submit them to the large language model interface to generate final function descriptions and annotations;
[0030] The feedback processing module is used to correct the module source code and comments according to the overall project specifications fed back by the large language model interface, so as to ensure the comprehensiveness and consistency of the module files and the project source code and comments.
[0031] Preferably, the source code processing module further includes a syntax parsing unit for performing syntax analysis on program module function descriptions and comments, extracting key information and formatting and submitting it to the large language model interface.
[0032] Preferably, the code generation module further includes a code template library for storing commonly used code templates so that the large language model interface can reference them when generating preliminary module source code, thereby improving the quality and consistency of the generated code.
[0033] The advantages of the present invention over the prior art are:
[0034] 1. Starting with the code function module description comment and ending with the code function module description comment (for example, C language comments start with / * and end with * / ), a large language model request is automatically initiated.
[0035] 2. Bidirectional large language model requests code completion. Forward annotation generates code, and by submitting annotations, the functions of code function modules and code snippets are understood, and the large language model is requested to provide the basic framework and logic code for sample function code completion. Reverse code correction annotations, by judging the closure of the completed code module, the last closure of the function module, or other introductions that meet the completion, the function module code segment is automatically submitted to the large language model for calculation, and revised annotations are generated to complete the missing details in the annotations. In addition, the annotation content is not limited to the current code module, but is combined with the code engineering annotation content to improve the reference of the current module in the code engineering, permission control, security precautions and other details. For example, traditionally, when writing an md5 algorithm function module, it is simply annotated that this module inputs a string and calculates the md5 value of the string. This method combines the entire software engineering project, improves the annotations, and the md5 value algorithm is called by function modules such as Login and FileMd5, and prompts that the security of md5 is weak, and recommends or prohibits the use of prompts based on the security level of the calling module.
[0036] 3. The submitted functional description comments and codes are calculated based on personal identity, and personalized large model calculation results are generated for priority recommendation. BRIEF DESCRIPTION OF THE DRAWINGS
[0037] Figure 1 is a flow chart of the method of the present invention;
[0038] Figure 2 It is a code association diagram in traditional technology;
[0039] Figure 3 is a schematic diagram of the code of step 1 in embodiment 2 of the present invention;
[0040] Figure 4 is a schematic diagram of the code of step 2 in embodiment 2 of the present invention;
[0041] Figure 5 is a schematic diagram of the code of step 3 in embodiment 2 of the present invention;
[0042] Figure 6 is a schematic diagram of the code of step 4 in embodiment 2 of the present invention;
[0043] Figure 7 is a schematic diagram of the code of step 5 in embodiment 2 of the present invention;
[0044] Figure 8 is a schematic diagram of feedback of step 5 in embodiment 2 of the present invention;
[0045] Fig. 9 is a schematic diagram of feedback of step 6 in embodiment 2 of the present invention;
[0046] Fig.10 This is a code diagram of step 6 in Example 2 of the present invention. DETAILED DESCRIPTION
[0047] The specific implementation of the present invention will be described below in conjunction with the accompanying drawings.
[0048] like Figure 1 Shown is a schematic diagram of the method of the present invention, comprising:
[0049] A method for supplementing code based on a two-way intelligent question-answering system based on a large language model comprises the following steps:
[0050] S1: Enter the program module function description and annotations, including the module name, function description, input and output parameter description, key algorithm flow and detailed description of special processing logic, and submit the module function description and annotations to the large language model interface after the annotation is closed or manually submitted. The large language model interface is a trained existing technology large model interface, such as ChatGPT, OpenAI Codex or Google BERT; the configuration reference example of the large language model interface includes the following steps:
[0051] 1. Get an API key: Get an API key from the corresponding large language model provider (such as OpenAI, Google).
[0052] 2. Interface configuration: Configure the API interface in the system, including setting the API key and configuring the interface address. For example, for OpenAI's ChatGPT, the interface address is https: / / api.openai.com / v1 / engines / davinci-codex / completions.
[0053] 3. Data formatting: Organize the module function description and comments in the format required by the large language model. For example, submit them in JSON format, including necessary fields such as prompt, max_tokens, temperature and other parameters.
[0054] 4. Call the interface: Call the large language model interface through HTTP POST request and receive the returned result. For example, use Python's requests library to send a request:
[0055] import requests
[0056] headers = {
[0057] "Authorization": f"Bearer {api_key}",
[0058] "Content-Type": "application / json"
[0059] }
[0060] data = {
[0061] "prompt": "Module function description and comments",
[0062] "max_tokens": 150,
[0063] "temperature": 0.7
[0064] }
[0065] response = requests.post(api_url, headers=headers, json=data)
[0066] result = response.json()
[0067] The module name is the name that specifically identifies the program module, such as "user authentication module" or "data processing module"; the functional description describes the module's functions and intended uses in detail. For example, "This module is used to verify user identity, provide login and logout functions, and manage user sessions"; it may include a description of the usage scenario, such as "The user enters the username and password for login verification, and enters the system homepage after success". The input and output parameter descriptions include input parameters: parameter name, data type, value range and meaning, such as "username (string, length 6-20 characters, used to identify the user), password (string, length 6-20 characters, used to verify the user's identity)"; output parameters: parameter name, data type, value range and meaning, such as "isAuthenticated (Boolean value, indicating whether the user has passed the verification)"; the key algorithm flow includes algorithm overview: providing an overall description of the algorithm, such as "encrypting the input password using the MD5 encryption algorithm and comparing it with the encrypted password stored in the database". Describe the various steps of the algorithm, such as: 1. Receive the username and password entered by the user; 2. Encrypt the input password using the MD5 algorithm, refer to the example:
[0068] import hashlib
[0069] def encrypt_password(password):
[0070] md5 = hashlib.md5()
[0071] md5.update(password.encode('utf-8'))
[0072] return md5.hexdigest()
[0073] encrypted_password = encrypt_password(user_input_password) ;
[0075] 3. Query the database for records that match the input username. Refer to the example:
[0076] query = "SELECT encrypted_password FROM users WHERE username = %s"
[0077] cursor.execute(query, (username,))
[0078] result = cursor.fetchone() ;
[0080] 4. Compare the encrypted value of the input password with the password value stored in the database, refer to the example:
[0081] if result and result[0] == encrypted_password:
[0082] return True
[0083] else:
[0084] return False ;
[0086] 5. Return the comparison result as the verification result. The special processing logic includes: error handling, for example: "If the user name does not exist, return the error message 'user name does not exist'", reference example:
[0087] if not user_record:
[0088] return {"error": "Username does not exist"} ;
[0090] Exception handling, for example: "If the database connection fails, throw a 'database connection exception' and log it", refer to the example:
[0091] import logging
[0092] try:
[0093] # Database Operations
[0094] except DatabaseConnectionError as e:
[0095] logging.error(f"Database connection exception: {e}")
[0096] raise DatabaseConnectionError("Database connection exception") ;
[0098] Boundary cases, for example: "Lock out users who have logged in incorrectly multiple times. Lock the account after the user enters an incorrect password five times in a row, and automatically unlock it after five minutes."
[0099] S2: Generate a preliminary module source code result through the large language model interface, the module source code result includes a basic code structure, function definition, parameter processing and preliminary implementation logic, and feed back the generated module source code to the developer for preliminary modification; the basic code structure specifically includes class definition, interface definition and module division, for example: "define UserAuthentication class and IUserAuthentication interface, which are respectively used to implement and standardize user authentication functions"; the function definition specifically includes function name, parameter type and its return value, for example: "define function validateUser(username: str, password: str) -> bool"; the parameter processing specifically includes parameter legitimacy check and preprocessing, for example: "in the validateUser function, check whether the username and password are empty, and perform format verification"; the preliminary implementation logic specifically includes core algorithms and key steps, for example: "in the validateUser function, use the MD5 algorithm to encrypt the input password, and compare the encryption result with the stored value in the database, and return the comparison result as the verification result".
[0100] S3: Submit the module source code after preliminary modification to the large language model interface again, and modify the source code and function annotations according to the feedback results of the large language model interface. The source code and function annotations include error detection, performance optimization suggestions, and evaluation of the rationality of code logic; the error detection is to use static analysis tools (such as Pylint, Flake8) and error detection suggestions provided by the large language model to automatically detect syntax errors, type errors, undefined variables, and unused variables in the source code, for example: "When submitting the source code, automatically run Pylint for code inspection, and correct all syntax errors and type errors according to the feedback results"; the performance optimization suggestion is to identify the performance bottlenecks in the code according to the feedback from the large language model and performance analysis tools (such as cProfile, Py-Spy), and provide specific optimization suggestions, for example: "In the preliminary generated source code, mark the code segments that may cause performance problems, such as frequent I / O operations, complex nested loops, etc., and recommend optimization strategies, such as using caches and reducing loop nesting levels";
[0101] Reference examples of marking frequent I / O operation codes:
[0102] # Frequent I / O operations
[0103] for record in records:
[0104] with open(record.file_path, 'r') as file:
[0105] process(file.read())
[0106] # Optimization strategy: Use cache
[0107] cache = {}
[0108] for record in records:
[0109] if record.file_path not in cache:
[0110] with open(record.file_path, 'r') as file:
[0111] cache[record.file_path] = file.read()
[0112] process(cache[record.file_path])
[0113] Marking complex nested loop code reference example:
[0114] Complex nested loops
[0115] for i in range(len(list1)):
[0116] for j in range(len(list2)):
[0117] process(list1[i], list2[j])
[0118] # Optimization strategy: reduce the nesting level
[0119] from itertools import product
[0120] for item1, item2 in product(list1, list2):
[0121] process(item1, item2)
[0122] The evaluation of the logical rationality of the code is to evaluate the logical rationality of the code through the logic check provided by the logic analysis tool and the large language model, ensure the correctness of the code execution path, and avoid logical loopholes, for example: "Use the unit testing framework (such as unittest, pytest) to write and run test cases, verify the correctness of the code logic, and correct the code logic according to the test results."
[0123] S4: Submit the corrected source code and functional annotations to the large language model interface, perform unified and standardized corrections on the entire project, generate module files and project source code, and the module files and project source code include unified code style, standardized naming rules, standardized annotation formats, and optimized code readability and maintainability; the unified code style is to use a unified code style guide and formatting tool to automatically format the code, such as using a Python style guide and using tools such as Black for automatic code formatting; the standardized naming rules are to use consistent naming rules, such as using PascalCase for class names and camelCase for function and variable names ; For example: "All class names should use upper camel case, such as UserAuthentication; all function and variable names should use lower camel case, such as validateUser, userName"; The standardization of the comment format adopts a unified comment format and document string standard, for example: "Each function must contain a complete document string to describe the purpose, parameters, return value and possible exceptions of the function"; The optimization of the readability and maintainability of the code is to review and optimize the code through code review and refactoring tools to ensure that the code structure is clear and the logic is concise, which is convenient for subsequent maintenance, for example: "Perform code reviews regularly, identify and fix potential code quality issues, optimize code structure, reduce duplicate code, and improve code readability."
[0124] S5: Save the revised module file and project source code, and submit them to the large language model interface to generate the final functional description and annotations, which include complete module usage instructions, detailed code annotations, boundary condition processing instructions and possible exception handling strategies; the complete module usage instructions describe the overall function and usage of the module, including how to initialize the module, call the main functions of the module, and the input and output of the module, for example: "User authentication module: responsible for verifying user identity and providing login and logout functions; the detailed code annotations add detailed annotations to each function and key code segment, explaining its purpose, input parameters, return value and execution logic; the boundary condition processing instructions describe the processing logic of the module under different boundary conditions in detail, for example: "If the username or password is empty, the validateUser function will return False.", "If the database connection fails, the function will throw a DatabaseConnectionError exception and record a log."; the possible exception handling strategy describes the processing strategy of the module when encountering an abnormal situation, including the specific exception type, exception capture and processing method.
[0125] S6: Submit the module files and project source code with the final functional description and comments to the large language model interface, and make corrections based on the overall project specification suggestions fed back by the large language model interface. The overall project specification fed back by the large language model interface provides detailed coding style, naming rules, structural suggestions, performance optimization, error handling, test coverage, and specific suggestions on readability and maintainability, ensuring comprehensiveness and consistency in project development. The steps include:
[0126] S601: Verify the comprehensiveness and consistency of module files and project source code with the final functional description and comments;
[0127] S602: Automatically update code comments to ensure that all comments accurately reflect the source code content;
[0128] S603: Check the dependency between functions and modules to ensure that the calling logic between modules is correct;
[0129] S604: Verify the correctness of cross-module calls to ensure the code consistency and integrity of the entire project.
[0130] In step S6, ensuring the comprehensiveness and consistency of the project source code and comments includes automatic updating of code comments, checking the dependencies between functions and modules, and verifying the correctness of cross-module calls; the automatic updating of code comments is to use comment generation tools to automatically generate and update code comments to ensure that the comment content is synchronized with the source code. For example, after the code is changed, Sphinx is automatically run to generate the latest documentation, and the new function parameters, return values and logic changes are synchronized to the comments. The specific reference steps are as follows:
[0131] 1. Configure Sphinx tool:
[0132] pip install sphinx
[0133] sphinx-quickstart
[0134] 2. Add documentation strings to your code:
[0135] def validateUser(username: str, password: str) -> bool:
[0136] """
[0137] Verify the user's identity.
[0138] parameter:
[0139] username (str): username
[0140] password (str): password
[0141] return:
[0142] bool: whether the user is authenticated
[0143] """
[0144] # Function implementation
[0145] 3. Automatically generate documents:
[0146] sphinx-apidoc -o docs / source .
[0147] make html
[0148] 4. Automatically update documents:
[0149] # Automatically run after each code change
[0150] make clean
[0151] make html
[0152] ; The check of the dependencies between functions and modules is to use static code analysis tools to check the dependencies between functions and modules to ensure that all dependencies are correct and there are no circular dependencies. For example, every time the code is submitted, SonarQube is automatically run to perform dependency analysis to identify and resolve potential circular dependencies or incorrect dependencies. The specific reference steps are as follows:
[0153] 1. Install and configure SonarQube:
[0154] docker run -d --name sonarqube -p 9000:9000 sonarqube
[0155] 2. Configure SonarQube to scan the project:
[0156] sonar-scanner \
[0157] -Dsonar.projectKey=my_project \
[0158] -Dsonar.sources=. \
[0159] -Dsonar.host.url=http: / / localhost:9000 \
[0160] -Dsonar.login=your_token
[0161] 3. Run SonarQube scan:
[0162] sonar-scanner
[0163] 4. Analyze the scan results to identify and resolve circular dependencies or incorrect dependencies.
[0164] The correctness verification of the cross-module call is to verify the correctness of the cross-module call through the unit test and integration test framework to ensure that the calling logic between modules is correct and error-free, for example: write unit test and integration test cases to cover the interface call scenarios between modules, automatically run these test cases and generate test reports; the specific reference steps are as follows:
[0165] 1. Choose a test framework, such as unittest or pytest;
[0166] 2. Write unit test cases:
[0167] import unittest
[0168] from module import validateUser
[0169] class TestUserAuthentication(unittest.TestCase):
[0170] def test_validate_user(self):
[0171] result = validateUser("test_user", "test_password")
[0172] self.assertTrue(result)
[0173] if __name__ == '__main__':
[0174] unittest.main()
[0175] 3. Write integration test cases to cover the interface call scenarios between modules:
[0176] def test_integration():
[0177] # Simulate cross-module calls
[0178] result = module1.functionA()
[0179] assert module2.functionB(result) == expected_output
[0180] 4. Automatically run test cases and generate test reports:
[0181] pytest --junitxml=report.xml.
[0182] The present invention also discloses a two-way intelligent question-answer code supplement system based on a large language model, comprising:
[0183] A source code processing module is used to parse the program module function description and comments, and submit the module function description and comments to the large language model interface after the comments are closed or manually submitted, including a syntax parsing unit, which is used to perform syntax analysis on the program module function description and comments, extract key information, and format and submit it to the large language model interface;
[0184] A code generation module, connected to the large language model interface, for generating a preliminary module source code result; the code generation module includes a code template library for storing commonly used code templates so that the large language model interface can reference them when generating the preliminary module source code, thereby improving the quality and consistency of the generated code;
[0185] A correction module, used to submit the module source code after preliminary modification to the large language model interface again, and to correct the source code and function annotations according to the feedback result of the large language model interface;
[0186] An overall project processing module, used to submit the revised module source code and function annotations to the large language model interface, and to perform unified and standardized revisions on the overall project;
[0187] A storage module, used to save the revised module files and engineering project source code, and submit them to the large language model interface to generate final function descriptions and annotations;
[0188] The feedback processing module is used to correct the module source code and comments according to the overall project specifications fed back by the large language model interface, so as to ensure the comprehensiveness and consistency of the module files and the project source code and comments.
[0189] Preferably, the source code processing module further includes a syntax parsing unit for performing syntax analysis on program module function descriptions and comments, extracting key information and formatting and submitting it to the large language model interface.
[0190] Preferably, the code generation module further includes a code template library for storing commonly used code templates so that the large language model interface can reference them when generating preliminary module source code, thereby improving the quality and consistency of the generated code.
[0191] Next, consider a specific example 1:
[0192] Embodiment 1:
[0193] Assume that a complex enterprise management system generally needs to implement functions such as user login, data management, report generation, etc. By using the bidirectional intelligent question-answering code supplement method and system based on a large language model of the present invention, development efficiency and code quality can be improved.
[0194] In the software development process, developers usually need to write a lot of code and add detailed comments to the code. These comments are used to explain the function and logic of the code and help other developers understand and maintain the code. However, the process of writing comments and code can be very time-consuming and prone to errors. Intelligent code completion technology based on large language models can automatically generate code and comments, reducing the burden on developers.
[0195] Step 1: Enter the program module function description and comments:
[0196] The developer starts writing a user login module. First, add function descriptions and comments to the code to describe the module's functions. For example:
[0197] ```c
[0198] / * User login module
[0199] * Function description: Implement user login function, verify username and password, and return login result
[0200] * Input: username, password
[0201] * Output: Login success or failure message
[0202] * /
[0203] ```
[0204] Step 2: Submit the function description and annotations to the large language model interface:
[0205] Developers submit these functional descriptions and comments to the large language model interface, which parses these descriptions and prepares to generate corresponding code.
[0206] Step 3: Generate and feedback the module source code results and make preliminary modifications:
[0207] The large language model generates a preliminary code framework and logic based on the functional description and comments. For example, the large language model may generate the following code:
[0208] ```c
[0209] #include<stdio.h>
[0210] #include<string.h>
[0211] / / User login function
[0212] int login(const char* username, const char* password) {
[0213] / / Here is the logic for verifying username and password
[0214] if (strcmp(username, "admin") == 0 && strcmp(password, "1234") ==0) {
[0215] return 1; / / Login successful
[0216] }
[0217] return 0; / / Login failed
[0218] }
[0219] Developers review the generated code and make necessary modifications and optimizations.
[0220] Step 4: Submit the corrected function module source code to the large language model interface.
[0221] The developer submits the corrected code back to the big language model interface. The big language model will generate and correct the corresponding comments based on the new code. For example, it may add more detailed comments to explain the function of each code segment:
[0222] ```c
[0223] #include<stdio.h>
[0224] #include<string.h>
[0225] / * User login function
[0226] * Function: Verify username and password
[0227] * Parameters: username, password
[0228] * Return value: 1 indicates successful login, 0 indicates failed login
[0229] * /
[0230] int login(const char* username, const char* password) {
[0231] / / Check if username and password match
[0232] if (strcmp(username, "admin") == 0 && strcmp(password, "1234") ==0) {
[0233] return 1; / / Login successful
[0234] }
[0235] return 0; / / Login failed
[0236] }
[0237] ```
[0238] Step 5: Overall project processing:
[0239] When the code and comments of all modules are generated and corrected, the developer submits the entire project to the big language model interface. The big language model will check the overall structure of the project to ensure that the code and comments of all modules meet the unified specifications. For example, it may add some global comments to explain the architecture and design of the entire project:
[0240] ```c
[0241] / * Enterprise Management System
[0242] * The system includes functional modules such as user login, data management, report generation, etc.
[0243] * User login module: implement user login function
[0244] * Data management module: manage enterprise data
[0245] * Report generation module: Generate enterprise reports
[0246] * /
[0247] ```
[0248] Step 6: Save the corrected files and project source code:
[0249] Finally, the developer saves the corrected files and project source code to the version control system, completing the entire code completion process.
[0250] Through the two-way intelligent question-and-answer code completion method and system of the present invention, the development team can greatly improve the efficiency and quality of code writing, reduce errors, and generate more detailed and useful comments to facilitate subsequent maintenance and development.
[0251] Example 2: Calculating the MD5 hash value of a password This example is explained with code screenshots.
[0252] Step 1: Enter the program module function description and comments:
[0253] Developers enter functional descriptions and comments of program modules in the editor, such as Figure 3 shown.
[0254] Step 2: Close the comments or manually submit the module function description and comments to the large model.
[0255] The comments are closed or the developer manually submits the module function description and comments to the large language model interface for processing, as shown in Figure 4.
[0256] Step 3: Import the source code results of the large model feedback module and modify them:
[0257] The large language model generates a preliminary code framework based on the submitted comments and feeds it back to the developers for preliminary modification. The preliminary generated code is shown in Figure 5.
[0258] Developers make necessary modifications and optimizations based on the feedback.
[0259] Step 4: Corrected source code of the functional module Manually submit the module or the file or all the source code of the project to the large model. The corrected code is shown in FIG6 .
[0260] Step 5: Introduce large model feedback to modify module source code and function annotations according to relevant specifications:
[0261] The system submits the corrected code to the large language model interface again, and further corrects the code and comments based on the feedback from the large language model. The feedback code and instructions are shown in Figures 7 and 8.
[0262] Step 6: Save the corrected file and submit the module file and project source code to the large model automatically or manually.
[0263] Step 7: Introduce the large model feedback. The module source code and comments are corrected according to the relevant specifications of the whole project. The screenshots of the large model language feedback results are shown in Figures 9 and 10.
[0264] Through the above specific embodiments, the actual application process of the code supplement method based on the large language model bidirectional intelligent question and answer is demonstrated. This method not only improves the efficiency and quality of code writing, but also ensures the comprehensiveness and consistency of code and comments, and is suitable for various software development projects.
[0265] The above description is only a preferred specific implementation manner of the present invention, but the protection scope of the present invention is not limited thereto. Any technician familiar with the technical field can make equivalent replacements or changes according to the technical scheme and inventive concept of the present invention within the technical scope disclosed by the present invention, which should be covered by the protection scope of the present invention.
Claims
1. A two-way intelligent question-answering code supplement method based on a large language model, characterized in that: The steps include: S1: Enter the program module function description and comments, which include the module name, function description, input and output parameter description, key algorithm flow and detailed description of special processing logic, and submit the module function description and comments to the large language model interface after the comments are closed or manually submitted; S2: Generate a preliminary module source code result through the large language model interface, the module source code result includes a basic code structure, function definition, parameter processing and preliminary implementation logic, and feed back the generated module source code result to the developer for preliminary modification; S3: Submitting the module source code result after preliminary modification to the large language model interface again, and correcting the source code and function annotations according to the feedback result of the large language model interface, wherein the process of correcting the source code and function annotations according to the feedback result of the large language model interface includes error detection, performance optimization suggestions, and evaluation of the rationality of code logic; S4: submitting the revised source code and functional annotations to the large language model interface, making unified and standardized revisions to the entire project, and generating module files and engineering project source codes, wherein the unified and standardized revisions to the entire project include unifying the code style, normalizing the naming rules, standardizing the annotation format, and optimizing the readability and maintainability of the code; S5: Save the module file and the project source code, and submit them to the large language model interface to generate a final function description and annotation, wherein the final function description and annotation include a complete module usage description, detailed code annotations, boundary condition processing instructions, and possible exception handling strategies; S6: Submitting the module file and the project source code together with the final functional description and annotations to the large language model interface, and making corrections based on the overall project specification suggestions fed back by the large language model interface, the steps comprising: S601: Verify the comprehensiveness and consistency of module files and project source code with the final functional description and comments; S602: Automatically update code comments to ensure that all comments accurately reflect the source code content; S603: Check the dependency between functions and modules to ensure that the calling logic between modules is correct; S604: Verify the correctness of cross-module calls to ensure the code consistency and integrity of the entire project.
2. According to claim 1, a two-way intelligent question-answering code supplement method based on a large language model is characterized in that: The functional description and annotations of the program module entered in step S1 specifically include the module name identifying the program module, a detailed description of the module's functions and intended uses, input and output parameter descriptions, detailed process steps of key algorithms, and a detailed description of special processing logic. The input and output parameter descriptions include parameter names, data types, value ranges, and meanings. The special processing logic includes error handling, exception handling, and boundary conditions.
3. According to the method of claim 1, the method is characterized in that: In step S2, the basic code structure specifically includes class definition, interface definition and module division; the function definition specifically includes function name, parameter type and its return value; the parameter processing specifically includes parameter validity check and preprocessing; the preliminary implementation logic specifically includes core algorithms and key steps.
4. According to claim 1, a two-way intelligent question-answering code supplement method based on a large language model is characterized in that: In step S4, the unification of the code style is to use a unified code style guide and formatting tool to automatically format the code; The standardization of the naming rules is to adopt consistent naming rules; the standardization of the comment format is to adopt a unified comment format and document string standard; the optimization of the readability and maintainability of the code is to perform code review and optimization through code review and refactoring tools.
5. According to the method of claim 1, the method is characterized in that: In step S3, the error detection is to use the error detection suggestions provided by the static analysis tool and the large language model to automatically detect syntax errors, type errors, undefined variables, and unused variables in the source code; the performance optimization suggestions are to identify performance bottlenecks in the code based on the feedback from the large language model and the performance analysis tool, and provide specific optimization suggestions; the evaluation of the logical rationality of the code is to evaluate the logical rationality of the code through the logic check provided by the logic analysis tool and the large language model, to ensure that the code execution path is correct and to avoid logical loopholes.
6. According to the method of claim 1, the method is characterized in that: In step S5, the complete module usage instructions describe the overall functions and usage methods of the module, including how to initialize the module, call the main functions of the module, and the input and output of the module; the detailed code comments add detailed comments to each function and key code segment, explaining its purpose, input parameters, return value and execution logic; the boundary condition processing instructions describe in detail the processing logic of the module under different boundary conditions; the possible exception handling strategy describes the processing strategy of the module when encountering abnormal situations, including specific exception types, exception capture and processing methods.
7. The method for supplementing code based on a two-way intelligent question and answer system based on a large language model according to claim 1, characterized in that: The automatic updating of code comments in S602 is specifically: using a comment generation tool to automatically generate and update code comments to ensure that the comment content is synchronized with the source code; the checking of dependencies between functions and modules in S603 is specifically: using a static code analysis tool to check the dependencies between functions and modules to ensure that all dependencies are correct and no circular dependencies occur; the verification of the correctness of cross-module calls in S604 is specifically: verifying the correctness of cross-module calls through unit testing and integration testing frameworks to ensure that the calling logic between modules is correct and error-free.
8. A two-way intelligent question-answering code supplement system based on a large language model, characterized in that: include: A source code processing module is used to receive and parse the function description and comments of the program module, wherein the function description and comments include the module name, function description, input and output parameter description, detailed description of key algorithm flow and special processing logic, and submit the above function description and comments to the large language model interface after the comment is closed or manually submitted; the source code processing module includes a syntax parsing unit, which is used to perform syntax analysis on the function description and comments, extract key technical information and submit it to the large language model interface after formatting; A code generation module, connected to the large language model interface, for generating preliminary module source code based on the functional description and annotations, wherein the preliminary module source code includes a basic code structure, function definition, parameter processing, and preliminary implementation logic; the code generation module includes a code template library for storing commonly used code templates so that the large language model interface can reference them when generating preliminary module source code, thereby improving the quality and consistency of generated code; A correction module, used to feed back the generated module source code to the developer for preliminary modification, and submit the module source code after preliminary modification to the large language model interface again, and modify the module source code after preliminary modification and related functional annotations according to the feedback result of the large language model interface, wherein the modification of the module source code after preliminary modification and related functional annotations includes error detection, performance optimization suggestions and evaluation of code logic rationality; The overall project processing module is used to submit the corrected module source code and function annotations to the large language model interface to perform unified and standardized corrections on the overall project and generate module files and engineering project source code. The unified and standardized corrections on the overall project include the unification of code style, the standardization of naming rules, the standardization of annotation formats, and the optimization of code readability and maintainability. A storage module, used to save the module files and project source code, and submit them to the large language model interface to generate final functional descriptions and comments, which include complete module usage instructions, detailed code comments, boundary condition processing instructions and possible exception handling strategies; The feedback processing module is used to further revise the module source code and comments according to the overall project specification suggestions fed back by the large language model interface, so as to ensure the comprehensiveness, consistency and completeness of the module files, engineering project source code and final functional description and comments.
