Code writing, checking and modifying method based on large model
Through a large-model-based code writing, verification, and modification method, the problems of low efficiency and lack of systematic verification in traditional code development are solved, and efficient and low-defect code generation and verification are achieved, which supports multiple languages and improves security.
Patent Information
- Application Number
- CN202510869428.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-06-26
- Publication Date
- 2025-10-14
AI Technical Summary
Traditional code development has low efficiency and high error rates. Existing tools are inflexible and lack a systematic verification and correction mechanism. The generated code often contains syntax errors, logical flaws and security vulnerabilities.
A fine-tuned large language model is used to parse user requirements and generate initial code. A static analysis engine is used to perform in-depth code review, including syntax tree verification, security vulnerability detection, and API dependency chain detection. A suite of test cases is executed in an isolated environment, operating indicators are monitored in real time, and the code is iteratively refactored based on defect analysis results until quality standards are met.
It reduces the code defect rate, improves the software development cycle, reduces labor costs, greatly improves the vulnerability detection rate, supports multiple languages and improves code quality.
Smart Images

Figure CN120780347A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of artificial intelligence technology, and in particular to a code writing, verification and modification method based on a large model. Background Art
[0002] Traditional code development relies on manual writing and debugging, which has problems of low efficiency and high error rate.
[0003] Existing code generation tools (such as template engines) have poor flexibility, static analysis tools (such as ESLint) cannot understand semantic logic, and testing tools (such as JUnit) require manual writing of use cases.
[0004] Although large language models can generate code, they lack a systematic verification and correction mechanism, and the generated code often contains grammatical errors, logical flaws, and security vulnerabilities.
[0005] Based on the above situation, the present invention proposes a code writing, verification and modification method based on a large model. Summary of the Invention
[0006] In order to remedy the deficiencies of the prior art, the present invention provides a simple and efficient method for writing, verifying and modifying code based on a large model.
[0007] The present invention is achieved through the following technical solutions:
[0008] A method for writing, verifying and modifying code based on a large model, characterized by comprising the following steps:
[0009] Step S1: Use a fine-tuned large language model to analyze user needs and generate multilingual initial code;
[0010] Step S2: Perform deep code review through a static analysis engine, including syntax tree verification, security vulnerability pattern matching, and API dependency chain detection;
[0011] Step S3: Execute the automatically generated test case set in an isolated environment, monitor the running indicators in real time, and generate a defect heat map;
[0012] Step S4: Based on the defect analysis results, the large model is driven to perform iterative code reconstruction until it is confirmed that the preset quality standards are met.
[0013] In step S1, the CodeBERT model is used to parse the user's natural language requirements and extract function points, input and output constraints, and boundary conditions;
[0014] Initial code generation: Based on the understanding results, the CodeX model is called to generate initial code in Python or Java;
[0015] In step S2, SonarQube is used to perform in-depth static analysis, and the process is as follows:
[0016] Step S2.1: Implement control flow anomaly detection based on the abstract syntax tree (AST). The process is as follows:
[0017] Control flow anomaly detection: Identifies potential anomalies in control flow, including unreachable code and infinite loops, by analyzing the abstract syntax tree of the code.
[0018] Syntax error detection: Use the AST (Abstract Syntax Tree Parser) parser to check for syntax errors in the code, such as missing colons, mismatched brackets, etc.
[0019] Output detection results: Generate a report that lists all detected exceptions and syntax errors and provides repair suggestions to ensure the logical correctness and grammatical standardization of the code;
[0020] Step S2.2, specification review, the process is as follows:
[0021] Naming convention check: Determine whether the code follows the naming convention of PEP8 (Python) or camelCase (such as Java, JavaScript);
[0022] Cyclomatic complexity detection: Calculate the cyclomatic complexity (McCabe complexity) of the code and evaluate the logical complexity of the code; when the cyclomatic complexity exceeds the custom threshold (such as >15), a warning is issued to prompt optimization of the code structure;
[0023] Duplicate code detection: Scans the code to see if there is duplicate code with a similarity of more than 70%. If so, it prompts the developer to refactor the code to reduce redundancy.
[0024] Through the above steps, ensure that the code complies with the naming conventions, has clear logic and is free of duplication and redundancy.
[0025] Step S2.3: Security vulnerability scanning. The process is as follows:
[0026] SQL injection risk detection: Identifies whether there are unparameterized SQL queries in the code, detects potential SQL injection risks, and prompts developers to use parameterized queries or precompiled statements to prevent malicious input attacks.
[0027] CVE / NVD vulnerability database comparison: Scans the dependent libraries and components used in the code in real time and compares them with the CVE (Common Vulnerabilities and Exposures) or NVD (National Vulnerability Database) vulnerability database. If a version with a known vulnerability is found, a warning is issued and an upgrade to a secure version is recommended.
[0028] Path traversal vulnerability detection: Checks whether there are unfiltered user input paths in the code to prevent path traversal attacks. If so, it prompts the developer to strictly verify and filter the input path to ensure security.
[0029] Through the above steps, you can comprehensively detect security risks in the code and prevent SQL injection, known vulnerabilities and path traversal attacks.
[0030] Step S2.4: Verify API compatibility through the dependency graph. The process is as follows:
[0031] Dependency library version conflict detection: Checks whether there are version conflicts in the dependency libraries used in the project (for example, different modules depend on different versions of the same library) to ensure that all dependency library versions are compatible and avoid runtime errors;
[0032] Deprecated API usage warning: Scans the code to see if deprecated APIs or methods are used. If so, a warning will be issued to prompt the developer to replace them with recommended alternatives.
[0033] Output problem report: Generate a problem report that lists all detected dependency library version conflicts and usage of deprecated APIs, and provides repair suggestions to help developers quickly resolve problems.
[0034] By following these steps, you can ensure the API compatibility and stability of your code and avoid potential runtime issues.
[0035] In step S3, the automated testing process based on the Pytest framework is as follows:
[0036] Step S3.1: Generate test cases, including:
[0037] Normal scenario: Generate standard input use cases to verify functional correctness;
[0038] Boundary scenarios: Testing extreme cases, including empty files, oversized files, and illegal listings;
[0039] Abnormal scenarios: simulate abnormal situations, including file non-existence and permission errors;
[0040] Step S3.2: Sandbox execution
[0041] Run code in containers to ensure environmental isolation and security, including the following scenarios:
[0042] Memory leak detection: Use the valgrind tool to detect memory leak problems;
[0043] Timeout execution processing: terminate tasks that take more than 2 seconds to execute;
[0044] Abnormal crash capture: capture abnormal crashes such as segmentation faults (segfault);
[0045] Step S3.3: Defect tracing
[0046] Combined with code coverage pytest-cov, locate uncovered code branches; through stack trace information, map the error code line and quickly locate the root cause of the defect;
[0047] Step S3.4: Output the test report, including the test case execution status, memory leak detection results, timed task records, abnormal crash logs, and defect location information, to help developers fix problems efficiently.
[0048] In step S4, the feedback correction and optimization process is as follows:
[0049] Step S4.1, Correction Suggestion Generation: Input the error log into the fine-tuned GPT-4 model to generate targeted correction suggestions;
[0050] Step S4.2, automatic iteration: loop steps S2-S3 until the code passes all checks;
[0051] Step S4.3, Human-Computer Collaboration: Visually display the code differences before and after modification to help developers understand the changes. Support decision tree optimization mechanism to provide optimization solution selection suggestions based on performance and readability requirements.
[0052] Step S4.4: After manual confirmation, generate high-quality code that complies with the ISO / IEC 5055 standard to ensure that the code is functionally correct, performance-optimized, and readable.
[0053] A large-model-based code writing, verification, and modification system for implementing the above method, including a requirements analysis and code generation module, a static verification and specification review module, a dynamic testing and defect location module, and a feedback correction and optimization module;
[0054] The requirements parsing and code generation module is responsible for parsing user requirements using a fine-tuned large language model and generating initial code in multiple languages.
[0055] Static verification and specification review module, responsible for performing deep code review through static analysis engine, including syntax tree verification, security vulnerability pattern matching and API dependency chain detection;
[0056] Dynamic testing and defect positioning module, responsible for executing automatically generated test case set in isolated environment, monitoring running indicators in real time, and generating defect heat map;
[0057] Feedback correction and optimization module, responsible for driving large model for iterative code restructuring based on defect analysis results until confirming that preset quality standards are met.
[0058] A code writing, checking and modifying device based on a large model, characterized by comprising a memory and a processor; the memory is used to store a computer program, and the processor is used to execute the computer program to realize the method steps described above.
[0059] A readable storage medium, characterized by: the readable storage medium stores a computer program, and the computer program is executed by a processor to realize the method steps described above.
[0060] The beneficial effects of the present application are: the code writing, checking and modifying method based on a large model is suitable for multiple languages, reduces the defect rate of the code, improves the software development cycle, reduces the labor cost, and greatly improves the vulnerability detection rate. BRIEF DESCRIPTION OF DRAWINGS
[0061] In order to more clearly illustrate the technical solutions in the embodiments of the present application or the prior art, the following will briefly introduce the drawings needed to be used in the embodiment or prior art description. Obviously, the drawings described below are some embodiments of the present application, and those skilled in the art can obtain other drawings according to these drawings without creative labor.
[0062] ATTACHMENT Figure 1 The present application is a code writing, checking and modifying method based on a large model. DETAILED DESCRIPTION
[0063] In order to make the person skilled in the art better understand the technical solutions in the present application, the technical solutions in the embodiments of the present application will be described clearly and completely below. Obviously, the described embodiments are only some of the embodiments of the present application, not all. Based on the embodiments in the present application, all other embodiments obtained by those skilled in the art without creative labor should belong to the scope of protection of the present application.
[0064] The code writing, checking and modifying method based on a large model comprises the following steps:
[0065] Step S1: Use a fine-tuned large language model to analyze user needs and generate multilingual initial code;
[0066] Step S2: Perform deep code review through a static analysis engine, including syntax tree verification, security vulnerability pattern matching, and API dependency chain detection;
[0067] Step S3: Execute the automatically generated test case set in an isolated environment, monitor the running indicators in real time, and generate a defect heat map;
[0068] Step S4: Based on the defect analysis results, the large model is driven to perform iterative code reconstruction until it is confirmed that the preset quality standards are met.
[0069] In step S1, the CodeBERT model is used to parse the user's natural language requirements and extract function points, input and output constraints, and boundary conditions;
[0070] Initial code generation: Based on the understanding results, the CodeX model is called to generate initial code in Python or Java;
[0071] Example: Input "Use Python to read a CSV file and calculate the average value of a column". The output is as follows.
[0072] import pandas as pd
[0073] def calculate_average(file_path,column_name):
[0074] data = pd.read_csv(file_path)
[0075] return data[column_name].mean()
[0076] In step S2, SonarQube is used to perform in-depth static analysis, and the process is as follows:
[0077] Step S2.1: Implement control flow anomaly detection based on the abstract syntax tree (AST). The process is as follows:
[0078] Control flow anomaly detection: Identifies potential anomalies in control flow, including unreachable code and infinite loops, by analyzing the abstract syntax tree of the code.
[0079] Syntax error detection: Use the AST (Abstract Syntax Tree Parser) parser to check for syntax errors in the code, such as missing colons, mismatched brackets, etc.
[0080] Output detection results: Generate a report that lists all detected exceptions and syntax errors and provides repair suggestions to ensure the logical correctness and grammatical standardization of the code;
[0081] Step S2.2, specification review, the process is as follows:
[0082] Naming convention check: Determine whether the code follows the naming convention of PEP8 (Python) or camelCase (such as Java, JavaScript);
[0083] For example, PEP8 requires variable names to use lowercase letters and underscore separators (my_variable), while camelCase requires variable names to start with a lowercase letter and have no separators (myVariable).
[0084] Cyclomatic complexity detection: Calculate the cyclomatic complexity (McCabe complexity) of the code and evaluate the logical complexity of the code; when the cyclomatic complexity exceeds the custom threshold (such as >15), a warning is issued to prompt optimization of the code structure;
[0085] Duplicate code detection: Scans the code to see if there is duplicate code with a similarity of more than 70%. If so, it prompts the developer to refactor the code to reduce redundancy.
[0086] Through the above steps, ensure that the code complies with the naming conventions, has clear logic and is free of duplication and redundancy.
[0087] Step S2.3: Security vulnerability scanning. The process is as follows:
[0088] CWE vulnerability pattern matching: Utilizes the CWE (Common Weakness Enumeration) database to identify possible security vulnerability patterns (such as buffer overflow, privilege escalation, etc.) in the code.
[0089] SQL injection risk detection: Identifies whether there are unparameterized SQL queries in the code, detects potential SQL injection risks, and prompts developers to use parameterized queries or precompiled statements to prevent malicious input attacks.
[0090] CVE / NVD vulnerability database comparison: Scans the dependent libraries and components used in the code in real time and compares them with the CVE (Common Vulnerabilities and Exposures) or NVD (National Vulnerability Database) vulnerability database. If a version with a known vulnerability is found, a warning is issued and an upgrade to a secure version is recommended.
[0091] Path traversal vulnerability detection: Checks whether there are unfiltered user input paths in the code to prevent path traversal attacks. If so, it prompts the developer to strictly verify and filter the input path to ensure security.
[0092] Through the above steps, you can comprehensively detect security risks in the code and prevent SQL injection, known vulnerabilities and path traversal attacks.
[0093] Step S2.4: Verify API compatibility through the dependency graph. The process is as follows:
[0094] Dependency library version conflict detection: Checks whether there are version conflicts in the dependency libraries used in the project (for example, different modules depend on different versions of the same library) to ensure that all dependency library versions are compatible and avoid runtime errors;
[0095] Deprecated API usage warning: Scans the code to see if deprecated APIs or methods are used. If so, a warning will be issued to prompt the developer to replace them with recommended alternatives;
[0096] Output problem report: Generate a problem report that lists all detected dependency library version conflicts and usage of deprecated APIs, and provides repair suggestions to help developers quickly resolve problems.
[0097] By following these steps, you can ensure the API compatibility and stability of your code and avoid potential runtime issues.
[0098] An example problem report is as follows:
[0099] {
[0100] "file":"calculate.py",
[0101] "line":3,
[0102] "issue":"Unchecked file input",
[0103] "severity":"CRITICAL",
[0104] "solution":"Add file extension validation"
[0105] }
[0106] In step S3, the automated testing process based on the Pytest framework is as follows:
[0107] Step S3.1: Generate test cases, including:
[0108] Normal scenario: Generate standard input use cases to verify functional correctness;
[0109] Boundary scenarios: Testing extreme cases, including empty files, oversized files, and illegal listings;
[0110] Abnormal scenarios: simulate abnormal situations, including file non-existence and permission errors;
[0111] Step S3.2: Sandbox execution
[0112] Run code in containers to ensure environmental isolation and security, including the following scenarios:
[0113] Memory leak detection: Use the valgrind tool to detect memory leak problems;
[0114] Timeout execution processing: terminate tasks that take more than 2 seconds to execute;
[0115] Abnormal crash capture: capture abnormal crashes such as segfault;
[0116] Step S3.3: Defect tracing
[0117] Combined with code coverage pytest-cov, locate uncovered code branches; through stack trace information, map the error code line and quickly locate the root cause of the defect;
[0118] Step S3.4: Output the test report, including the test case execution status, memory leak detection results, timed task records, abnormal crash logs, and defect location information, to help developers fix problems efficiently.
[0119] The output test report is as follows:
[0120] [FAIL]test_invalid_column:
[0121] File"test_calculate.py",line 25,in test_invalid_column
[0122] calculate_average("data.csv","invalid")
[0123] File"calculate.py",line 4,in calculate_average
[0124] return data[column_name].mean()
[0125] KeyError:'Column'invalid'not found'
[0126] In step S4, the feedback correction and optimization process is as follows:
[0127] Step S4.1, generate correction suggestions: Input the error log into the fine-tuned GPT-4 model to generate targeted correction suggestions; the output example is as follows:
[0128] def calculate_average(file_path,column_name):
[0129] +if not os.path.exists(file_path):
[0130] +raise FileNotFoundError(f"{file_path}not exist")
[0131] data = pd.read_csv(file_path)
[0132] +if column_name not in data.columns:
[0133] +raise ValueError(f"Invalid column:{column_name}")
[0134] return data[column_name].mean()
[0135] Step S4.2, automatic iteration: loop steps S2-S3 until the code passes all checks;
[0136] Step S4.3, Human-Computer Collaboration: Visually display the code differences before and after modification to help developers understand the changes. Support decision tree optimization mechanism to provide optimization solution selection suggestions based on performance and readability requirements.
[0137] Step S4.4: After manual confirmation, generate high-quality code that complies with the ISO / IEC 5055 standard to ensure that the code is functionally correct, performance-optimized, and readable.
[0138] The large-model-based code writing, verification, and modification system is used to implement the above method, including a requirements analysis and code generation module, a static verification and specification review module, a dynamic testing and defect location module, and a feedback correction and optimization module;
[0139] The requirements parsing and code generation module is responsible for parsing user requirements using a fine-tuned large language model and generating initial code in multiple languages.
[0140] The static verification and specification review module is responsible for performing in-depth code review through the static analysis engine, including syntax tree verification, security vulnerability pattern matching, and API dependency chain detection;
[0141] The dynamic testing and defect location module is responsible for executing automatically generated test case sets in an isolated environment, monitoring operating indicators in real time, and generating defect heat maps;
[0142] The feedback correction and optimization module is responsible for driving the large model to perform iterative code reconstruction based on the defect analysis results until it is confirmed that the preset quality standards are met.
[0143] The code writing, checking and modifying device based on the large model includes a memory and a processor; the memory is used to store computer programs, and the processor is used to implement the above-mentioned method steps when executing the computer program.
[0144] The readable storage medium stores a computer program, which implements the above method steps when executed by a processor.
[0145] Compared with existing technologies, this large-model-based code writing, verification, and modification method has the following characteristics:
[0146] First, the defect rate is reduced: triple verification reduces the code defect rate to <0.5% (the industry average is 5%).
[0147] Second, efficiency improvement: the development cycle is shortened by 60%, and use case generation takes less than 200ms.
[0148] Third, cost savings: Reduce manual code review workload by 70%.
[0149] Fourth, strong adaptability: supports 10+ languages including Java / Python / C++.
[0150] Fifth, security enhancement: OWASP TOP10 vulnerability detection rate >98%.
[0151] The embodiment described above is only one specific implementation of the present invention. Common changes and substitutions made by those skilled in the art within the scope of the technical solution of the present invention should be included in the protection scope of the present invention.
Claims
1. A code writing, verification and modification method based on a large model, characterized by: The following steps are involved: Step S1: Use a fine-tuned large language model to analyze user needs and generate multilingual initial code; Step S2: Perform deep code review through a static analysis engine, including syntax tree verification, security vulnerability pattern matching, and API dependency chain detection; Step S3: Execute the automatically generated test case set in an isolated environment, monitor the running indicators in real time, and generate a defect heat map; Step S4: Based on the defect analysis results, the large model is driven to perform iterative code reconstruction until it is confirmed that the preset quality standards are met.
2. The code writing, verification and modification method based on a large model according to claim 1 is characterized in that: In step S1, the CodeBERT model is used to parse the user's natural language requirements and extract function points, input and output constraints, and boundary conditions; Initial code generation: Based on the understanding results, the CodeX model is called to generate initial code in Python or Java.
3. The code writing, verification and modification method based on a large model according to claim 1 is characterized in that: In step S2, SonarQube is used to perform in-depth static analysis, and the process is as follows: Step S2.1: Implement control flow anomaly detection based on the abstract syntax tree. The process is as follows: Control flow anomaly detection: Identifies control flow anomalies, including unreachable code and infinite loops, by analyzing the abstract syntax tree of the code. Syntax error detection: Use AST parser to check syntax errors in the code; Output detection results: Generate a report that lists all detected exceptions and syntax errors and provides repair suggestions to ensure the logical correctness and grammatical standardization of the code; Step S2.2, specification review, the process is as follows: Naming convention check: determine whether the code follows the PEP8 or camelCase naming convention; Cyclomatic complexity detection: calculate the cyclomatic complexity of the code and evaluate the logical complexity of the code; When the cyclomatic complexity exceeds the custom threshold, a warning is issued to prompt you to optimize the code structure; Duplicate code detection: Scans the code to see if there is duplicate code with a similarity of more than 70%. If so, it prompts the developer to refactor the code to reduce redundancy. Step S2.3: Security vulnerability scanning. The process is as follows: SQL injection risk detection: Identifies whether there are unparameterized SQL queries in the code, detects potential SQL injection risks, and prompts developers to use parameterized queries or precompiled statements to prevent malicious input attacks. CVE / NVD vulnerability database comparison: Scans the dependent libraries and components used in the code in real time and compares them with the CVE or NVD vulnerability database. If a version with a known vulnerability is found, a warning is issued and an upgrade to a secure version is recommended. Path traversal vulnerability detection: Checks whether there are unfiltered user input paths in the code to prevent path traversal attacks. If so, it prompts the developer to strictly verify and filter the input path to ensure security. Step S2.4: Verify API compatibility through the dependency graph. The process is as follows: Dependency library version conflict detection: Check whether there are version conflicts in the dependency libraries used in the project to ensure that all dependency library versions are compatible and avoid runtime errors; Deprecated API usage warning: Scans the code to see if deprecated APIs or methods are used. If so, a warning will be issued to prompt the developer to replace them with recommended alternatives. Output problem report: Generate a problem report that lists all detected dependency library version conflicts and usage of deprecated APIs, and provides repair suggestions.
4. The method for writing, verifying, and modifying code based on a large model according to claim 1, characterized in that: In step S3, the automated testing process based on the Pytest framework is as follows: Step S3.1: Generate test cases, including: Normal scenario: Generate standard input use cases to verify functional correctness; Boundary scenarios: Testing extreme cases, including empty files, oversized files, and illegal listings; Abnormal scenarios: simulate abnormal situations, including file non-existence and permission errors; Step S3.2: Sandbox execution Run code in containers to ensure environmental isolation and security, including the following scenarios: Memory leak detection: Use the valgrind tool to detect memory leak problems; Timeout execution processing: terminate tasks that take more than 2 seconds to execute; Abnormal crash capture: capture abnormal crash conditions; Step S3.3: Defect tracing Combined with code coverage pytest-cov to locate uncovered code branches; through stack trace information, map the error code line and locate the root cause of the defect; Step S3.4: Output the test report, including the test case execution status, memory leak detection results, timed task records, abnormal crash logs, and defect location information.
5. The method for writing, verifying and modifying code based on a large model according to claim 1, characterized in that: In step S4, the feedback correction and optimization process is as follows: Step S4.1, Correction Suggestion Generation: Input the error log into the fine-tuned GPT-4 model to generate targeted correction suggestions; Step S4.2, automatic iteration: loop steps S2-S3 until the code passes all checks; Step S4.3, Human-computer collaboration: Visually display the code differences before and after modification to help developers understand the changes; Supports decision tree optimization mechanism and provides optimization solution selection suggestions based on performance and readability requirements; Step S4.4: After manual confirmation, generate high-quality code that complies with the ISO / IEC 5055 standard to ensure that the code is functionally correct, performance-optimized, and readable.
6. A code writing, verification and modification system based on a large model, characterized by: Used to implement the method according to any one of claims 1 to 5, comprising a requirement parsing and code generation module, a static verification and specification review module, a dynamic testing and defect location module, and a feedback correction and optimization module; The requirements parsing and code generation module is responsible for parsing user requirements using a fine-tuned large language model and generating initial code in multiple languages. The static verification and specification review module is responsible for performing in-depth code review through the static analysis engine, including syntax tree verification, security vulnerability pattern matching, and API dependency chain detection; The dynamic testing and defect location module is responsible for executing automatically generated test case sets in an isolated environment, monitoring operating indicators in real time, and generating defect heat maps; The feedback correction and optimization module is responsible for driving the large model to perform iterative code reconstruction based on the defect analysis results until it is confirmed that the preset quality standards are met.
7. A code writing, verification and modification device based on a large model, characterized by: The method comprises a memory and a processor; the memory is used to store a computer program, and the processor is used to implement the method steps according to any one of claims 1 to 5 when executing the computer program.
8. A readable storage medium, characterized in that: The readable storage medium stores a computer program, which, when executed by a processor, implements the method steps according to any one of claims 1 to 5.
Citation Information
Cited By
Automobile industry code quality automatic compliance method based on large language model
CN121501324A
Multi-language code specification and security vulnerability synchronous scanning method
CN121525053A