Code generation method based on reasoning time extension

Through a two-step code generation method based on reasoning time extension, an initial code draft is generated and optimized, or a knowledge base is built using external information for similarity retrieval. This solves the shortcomings of AI-assisted code tools in API calls and version compatibility, improves the accuracy and compatibility of code generation, and improves development efficiency and system stability.

CN120803423APending Publication Date: 2025-10-17SOUTHEAST UNIV
View PDF 0 Cites 1 Cited by

Patent Information

Application Number
CN202510925078.2
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-07-04
Publication Date
2025-10-17

AI Technical Summary

Technical Problem

When faced with complex actual development needs, existing AI-assisted code tools lack the ability to collaborate across language API ecosystems, the ability to perceive dynamic runtime API constraints, and the ability to adapt to the compatibility of multiple versions of libraries for rapid iteration. This leads to inaccurate code generation and version incompatibility, and is unable to meet the software development requirements for code accuracy, compatibility, and efficiency.

Method used

A two-step code generation method based on inference time expansion is adopted. First, an initial code draft is generated. Then, API call accuracy and version compatibility are optimized through a large model, or a structured knowledge base is built using external information for similarity retrieval and deep optimization to ensure the accuracy and compatibility of code generation.

Benefits of technology

It significantly improves the accuracy and compatibility of code generation, reduces memory leaks, lowers development costs, improves development efficiency and system stability, and adapts to high-frequency iterative technology stack adaptation and multi-library collaborative calling scenarios.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120803423A_ABST
    Figure CN120803423A_ABST
Patent Text Reader

Abstract

The invention relates to a code generation method based on reasoning time extension. The method comprises the following steps: 1, in a scene without external information: step 1, generating an initial code draft with API (Application Program Interface) calling; 2, the large model considers the influence of PythonAPI version evolution on code migration according to a given rough code, library requirements and version constraints, and generates a refined code with correct API calling; and 2, introducing a rough code retrieval scene by using external information: step 1, capturing a Python library from PyPI and GitHub, and constructing an external knowledge base; the method comprises the following steps of: 1, generating a rough code snippet, 2, generating a rough code snippet, and 3, generating a refined code snippet subjected to knowledge enhancement by a large model according to a given rough code, library requirements, version constraints and retrieved knowledge snippets. The method can improve the correctness of the API, is compatible with a deployment standard, and improves the code generation capability of a large model when the large model deals with API demand evolution.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The application belongs to the technical field of code generation and application of large language models, and particularly relates to a code generation method based on reasoning time expansion in two scenarios of no external information and using external information and introducing rough code retrieval. BACKGROUND

[0002] In the modern software development system, the importance of automatic code generation technology is increasing day by day. With the continuous expansion of the scale of software projects and the continuous rise of the complexity of functions, the traditional manual code writing method exposes many drawbacks. On the one hand, the efficiency of manual code writing is extremely low, and the development cycle is long, which is difficult to meet the market demand of rapid iteration; on the other hand, errors caused by human factors frequently occur, and the quality of the code is uneven, and the maintenance cost is high. Therefore, automatic code generation technology has become a key research direction to solve these problems, and has attracted widespread attention from the academic and industrial circles. In recent years, large language models (LLMs) have emerged in the field of code generation due to their strong language understanding and generation capabilities. In the HumanEval benchmark test scene, LLMs can generate corresponding code according to natural language instructions, showing certain application potential. However, when facing actual software development tasks, the limitations of LLMs are also gradually highlighted.

[0003] In practical development, code version control is a thorny problem. Different versions of software libraries may have significant differences in API design, such as function name changes, parameter order adjustments, and changes in implementation methods. This requires the generated code to accurately adapt to these changes and ensure stable operation in different library environments. However, existing methods based on LLMs for directly generating code are not up to the task when dealing with code version control issues, often generating code that is incompatible with the target library version, leading to program errors. Multi-API calling scenarios are also complex and varied. In a software project, multiple APIs from different libraries are often called to implement rich functions. How to accurately filter out the interfaces that meet the requirements from numerous APIs and correctly call them is a major challenge in code generation. Current code generation techniques often have problems such as improper API selection, incorrect calling order, and unreasonable parameter passing when dealing with multi-API calling, seriously affecting the correctness and performance of the code. Existing research can be divided into two categories. One is to rely solely on LLMs' internal knowledge for code generation, such as early Codex and GPT-3. This method is difficult to generate high-quality code that meets actual needs due to the lack of external knowledge when faced with complex situations in actual development. The other is to use retrieval enhancement, such as RECODE and REDCODER, which retrieve relevant information from external data sources to assist code generation. However, both methods still have many difficulties in ensuring accurate API calling for specific library versions and handling multi-API calling. For example, during the retrieval process, the retrieved information may not match the actual needs due to the differences between natural language and code structure, affecting the quality of code generation. In addition, although structured reasoning (such as Chain of Thought prompting and ReAct) provides a new approach to code generation by breaking down tasks into multiple steps or using API queries to optimize output, it has not made substantial breakthroughs in solving the core problem of API calling accuracy. In summary, existing AI-assisted code development tools in the industry, such as GitHub Copilot, MarsCode, and The AI Code Editor, lack the ability to coordinate across language API ecosystems, dynamically perceive runtime API constraints, quickly iterate multi-version library API compatibility, and ensure logical consistency in multi-library coordination. They cannot effectively meet the requirements of software development for code accuracy, compatibility, and efficiency. Therefore, developing a new code generation method to improve the quality and efficiency of code generation, ensuring the accuracy and version compatibility of API calling, and evolving AI code tools from "code completion assistance" to "industrial-level API calling solutions" is an important problem that needs to be addressed in the current software development field. SUMMARY

[0004] To solve the problems in the prior art, the purpose of the present application is to provide a two-step code generation method based on reasoning time extension in two scenarios of no external information and using external information and introducing rough code retrieval, to solve the dynamic knowledge matching failure problems such as inaccuracy and version incompatibility of existing AI assisted code tools such as GitHub Copilot, MarsCode, The AI Code Editor, etc. when API is called. Compared with the existing code generation technology, the two-step code generation method based on reasoning time extension reduces the memory leakage rate, realizes large-scale deployment, ensures the compliance of the development system, enables the developer to focus on the core business logic development, thereby speeding up the development process, while avoiding potential high penalties and manual debugging budget, significantly optimizing the development cost.

[0005] To achieve the above purpose, the technical scheme of the present application is as follows: a code generation method based on reasoning time extension, which is divided into two cases,

[0006] Case 1: No external information scenario:

[0007] The present application comprises the following steps:

[0008] Step 1: Generate an initial code draft with API calls: In the software development process, when facing a code generation task, the first problem encountered is the missing code segment. Given the missing code segment C m and library requirements R l , the model undertakes the task of generating a rough code segment C r =f(C m ,R l ).

[0009] Based on the word-level, line-level and block-level mask settings of the data set, the rough code C r generated by the model preliminarily meets the task requirements and builds a basic code framework. However, since this stage is only a preliminary construction, the code is not optimized in depth, so C r may contain various problems, such as API errors, possible misspelling of function names, incorrect parameter passing; version mismatch, using an API version that does not meet the requirements of the current project; and other inconsistencies, such as incoherent code logic, etc.

[0010] Step 2: The large model generates refined code according to the given rough code, library requirements and version constraints, considering the impact of Python API version evolution on code migration: the rough code C r generated in step 1, the explicit library requirements R l and the strict version constraints Vc As input provided to the large model. The large model fully considers the impact of Python API version evolution on code migration during processing. With the continuous updating and iteration of Python libraries, the functions, usage, and version compatibility of the API may change. The large model, according to the version constraint V c and library requirements R l , conducts comprehensive and meticulous optimization on the rough code C r . It deeply analyzes the code structure and API call logic, accurately identifies and corrects API errors in the code, ensuring the correctness of function calls. At the same time, the large model also optimizes the code to make it compatible with deployment standards, covering code performance optimization, security enhancement, and rational use of resources. The final refined code C f = f(C r , R l , V c ) integrates these necessary modifications, significantly improving the correctness of the API and compatibility with deployment standards, ensuring that the code can run stably and efficiently in actual production environments.

[0011] Case two, use external information, introduce rough code retrieval scenarios:

[0012] Step 1: Grab Python libraries from PyPI and GitHub, extract source code across versions, store library name, version, file path, and code metadata in JSON format, and build an external knowledge base: In order to fully utilize external information to improve code generation quality, the invention first constructs a structured knowledge base for enhanced code retrieval. With the help of powerful automated scripts, Python libraries are widely crawled from the Python Package Index (PyPI) and GitHub, two important code resource platforms. PyPI is an important repository of software packages in the Python ecosystem, storing a wealth of open-source libraries; GitHub brings together code projects contributed by developers around the world, containing a wealth of code resources. During the crawling process, for each Python library, extract the source code of different versions, because different versions of the library have differences in functionality and API design, obtaining multiple versions of the source code helps to fully understand the evolution process and characteristics of different versions of the library. The extracted library name, version, file path, and code metadata are stored in JSON format, which has good readability and scalability, facilitating subsequent data processing and retrieval. Each entry contains multiple application program interface (API) definitions, function signatures, and usage patterns specific to each library version, providing rich and accurate reference information for subsequent code generation.

[0013] Step 2: Generate a rough code snippet and use it as a query to retrieve relevant code snippets from an external knowledge base: During the code generation process, a rough code snippet C is first generated by the model r . This rough code snippet C r is a preliminary code framework generated based on task requirements and contains the intention to call specific libraries, but the calling part is not complete or accurate. For example, in a data processing task, the generated rough code may contain a call to the read CSV file function in the pandas library, but the function parameters are not determined, or the called function may not be the most suitable API for the current task. To solve the consistency problem, when retrieving code snippets from an external knowledge base, a code-based query method is used, abandoning the natural language-dependent retrieval method. The generated rough code C r is used as the query content, and relevant knowledge snippets are retrieved from the external knowledge base through similarity search. In this process, advanced similarity measurement algorithms are used to obtain the most matching code snippet k i , thereby reducing retrieval errors caused by the mismatch between natural language and code structure. The retrieval process can be represented by the formula

[0014]

[0015] , where k i represents the code snippet in the knowledge base, and V represents the most relevant code snippet retrieved based on similarity measurement.

[0016] Step 3: The model generates knowledge-enhanced refined code based on the given rough code, library requirements, version constraints, and retrieved knowledge snippets: The rough code C r , library requirements R l , version constraints V c , and retrieved knowledge snippets V are input into the large model. The large model combines these rich information to deeply optimize the code. The large model deeply analyzes the retrieved knowledge snippets V, extracts the correct API usage and code logic, and integrates them into the rough code C r , and modifies and perfects the API calls. At the same time, the large model ensures that the generated code meets the specific requirements of the project based on version constraints V c and library requirements R l . If the project requires the use of a specific version of the library, and the usage of some APIs in that version has changed, the large model will adjust the code accordingly to ensure that the code can run correctly in that version of the library environment. After a series of processes, the knowledge-enhanced refined code snippet C f = f(C r , R l , V cV). This code not only improves the correctness of the application program interface (API) with external information, but also ensures better compatibility with production-level requirements, meeting the strict requirements of actual software development projects for code quality and performance.

[0017] An electronic device comprising a memory, a processor, and a computer program stored on the memory and executable on the processor, the processor implementing the inference time extension-based code generation method when executing the program.

[0018] A computer-readable storage medium having stored thereon computer instructions that, when executed by a processor, implement the inference time extension-based code generation method.

[0019] Compared with the prior art, the present application has the following advantages:

[0020] 1. An innovative two-step code generation framework based on inference time extension is proposed, which formulates differentiated code generation strategies for different scenarios to improve industrial development efficiency: in the absence of external information, an initial code draft is generated through multi-level semantic analysis of code structure (such as variable scope and control flow logic), and then the built-in dynamic verification mechanism of the large model is used to optimize the logical accuracy and version compatibility of API calls. For example, when focusing on tasks such as quantitative trading strategy coding and risk control model deployment in the financial technology field, the API call logic can be optimized for financial APIs such as market data and fund clearing, and the interface version can be adapted to iterations. In the presence of external information, a structured knowledge base containing library version change logs, enterprise private API documents, and other content is first constructed, and then a refined retrieval method based on code features (such as function signatures and parameter constraints) is used to achieve knowledge-enhanced code generation. For example, a structured knowledge base containing financial library version change logs and internal risk control models and customer information interfaces is constructed to ensure accurate execution of instructions in high-frequency trading system iterations and intelligent risk control development scenarios. Combined with industrial application practice, this framework can significantly improve the accuracy and compatibility of code generation in complex scenarios, helping enterprises achieve a breakthrough in both development efficiency and system stability in scenarios such as high-frequency iteration technology stack adaptation and multi-library collaborative calling.

[0021] 2. In industrial software development, this solution significantly improves the engineering practice value in complex scenarios by integrating API call accuracy and version compatibility throughout the code generation process: In the face of high-frequency iteration of AI frameworks, the solution dynamically identifies changes in the API signature of the target version, automatically generates compatible code, and avoids the time-consuming and error-prone manual follow-up changes; Through multi-level semantic analysis, it avoids destructive updates of some libraries in advance, reducing the debugging cost caused by version incompatibility. Compared with existing technologies, this solution breaks through the limitations of traditional LLMs relying on static knowledge bases, has better development scene adaptability, and through dynamic verification and retrieval of reasoning time, it shows higher engineering practicability in complex dependency processing, emerging feature adaptation, and compliance guarantee scenarios. BRIEF DESCRIPTION OF DRAWINGS

[0022] Figure 1 The two-step code generation method flowchart based on reasoning time extension in the invention in the two scenarios of no external information and using external information and introducing rough code retrieval. DETAILED DESCRIPTION

[0023] To further clarify the technical purpose, scheme and advantages of the present application, the present application will be described in detail below in conjunction with the drawings. The following examples are only used to more clearly illustrate the technical scheme of the present application, and cannot limit the protection scope of the present application. All other examples obtained by those skilled in the art without creative labor fall within the protection scope of the present application.

[0024] The above is only a general description of the technical scheme of the present application. In order to clearly explain the technical means of the present application and facilitate implementation according to the description, and so that the above purpose, other characteristics and advantages of the present application are easier to understand, the specific implementation manner is as follows.

[0025] Example 1: The two-step code generation method based on reasoning time extension of the present application includes the following steps:

[0026] Case one, no external information scenario

[0027] Step 1, generate an initial code draft with API calls;

[0028] In the software development process, when facing a code generation task, the first encountered situation is the missing code fragment. Given the missing code fragment C m and library requirements R l , the model starts to generate a rough code fragment C r = f(C m , R l). This process can be further divided into two stages, with the missing code fragment generation stage being crucial. The overall framework of the code conforms to the syntax specifications of the target programming language, such as Python's function definition structure, class declaration format, etc., and the key logical flow is complete, including core code blocks required to solve tasks, such as loops, conditional judgments, and other control structures.

[0029] However, since this stage is only a preliminary construction, the code has not been deeply optimized, so the C r may contain various problems, such as API errors, which may manifest as incorrect function name spelling, incorrect parameter passing; version mismatch, which may use an API version that does not meet the current project requirements; and other inconsistencies, such as inconsistent code logic, mismatched variable definitions and usage, etc. Taking the torch library as an example, according to the task description and library version torch == 1.4, the large model generates a rough code fragment, such as:

[0030] def bar():

[0031] cb = torch.createResolutionCallback()

[0032] print(cb("foo") > 1)

[0033] The rough code fragment here only builds a preliminary code framework, which may have problems such as inaccurate API calls (such as torch.createResolutionCallback, which may not be an actual existing and correct API).

[0034] Step 2, the large model generates refined code with correct API calls based on the given rough code, library requirements, and version constraints, considering the impact of Python API version evolution on code migration.

[0035] The rough code C r generated in step 1, the explicit library requirements R l and the strict version constraints V c are input to the large model for processing. The large model fully considers the impact of Python API version evolution on code migration during optimization. With the continuous updating of Python libraries, the functionality, usage, and version compatibility of APIs may change. The large model, based on version constraints V c and library requirements R l , optimizes the rough code C rCarry out comprehensive and detailed optimization. It deeply analyzes the code structure and API call logic, accurately locates and corrects API errors, and ensures the accuracy of function calls. At the same time, the large model will also optimize the code to make it meet the deployment standards, covering code performance optimization, security improvement, rational use of resources and other aspects. In summary, refined reasoning includes the following goals: API correctness correction requires replacing API calls in the rough code that are incompatible with the target library version and verifying the parameter type and quantity to ensure consistency with the documentation. Structural enhancements must be integrated into the containerization support code and insert parameter type range verification logic. Version compatibility adaptation generates compatible dependency declarations for API changes specific to the target library version to ensure that the code can be reproduced. For example, if the correct callback function of torch in version 1.4 is torch.createResolutionCallbackFromFrame, the large model will correct torch.some_callback() in the rough code to torch.createResolutionCallbackFromFrame, and further improve other parts of the code, such as adding necessary parameter settings and error handling. After this series of processing, the refined code C is finally generated. f =f(C r ,R l ,V c ) incorporates these necessary modifications:

[0036] def bar():

[0037] cb=torch.createResolutionCallbackFromFrame()

[0038] result = cb("foo")

[0039] if isinstance(result,(int,float)):

[0040] print(result>1)

[0041] else:

[0042] print("The result is not a numeric type and cannot be compared")

[0043] The correctness of the API and its compatibility with deployment standards have been significantly improved, ensuring that the code can run stably and efficiently in the actual production environment.

[0044] Case 2: Using external information and introducing rough code retrieval scenarios.

[0045] Step 1: Python libraries are scraped from PyPI and GitHub, and source code is extracted across versions. Metadata such as library name, version, file path, and code are stored in JSON format. An external knowledge base is constructed.

[0046] To fully utilize external information to improve code generation quality, the invention first conducts structured knowledge base construction for search-enhanced code generation. With the powerful capabilities of automated scripts, Python libraries are widely scraped from the Python Package Index (PyPI) and GitHub, two important code resource platforms. PyPI serves as an important repository of software packages in the Python ecosystem, storing a wealth of open-source library resources; GitHub brings together various high-quality code projects contributed by developers around the world. During the scraping process, for each Python library, source code is extracted for different versions. Because different versions of the library differ in functionality and API design, obtaining multiple versions of the source code helps to fully understand the evolution of the library and the characteristics of different versions. The extracted metadata such as library name, version, file path, and code are stored in JSON format, which has good readability and scalability, facilitating subsequent data processing and retrieval. By establishing a semantic index based on code snippets for the knowledge base, multi-dimensional quick retrieval is supported through function names, parameter types, and version numbers. This structured knowledge base ensures that the model can retrieve version-specific API definitions and usage patterns through rough code retrieval during subsequent code generation. Each entry contains multiple application programming interface (API) definitions, function signatures, and usage patterns specific to each library version, providing rich and accurate reference information for subsequent code generation.

[0047] Step 2: A rough code snippet is generated, which is used as a query to retrieve relevant code snippets from the external knowledge base through similarity retrieval.

[0048] During code generation, the model first generates a rough code snippet C r . This rough code snippet C r is a preliminary code framework generated according to the task requirements, which contains the intention to call a specific library, but the calling part is not complete or accurate. For example, when the given task is to write a piece of code with the function of "printing a specific callback result according to the specified library version". Taking the accelerate library as an example, the large model generates a rough code snippet based on the task description and library version accelerate == 0.8.0.

[0049] The rough code snippet here is just a preliminary framework for the code, and there may be inaccuracies in API calls (such as init_weights, which may not be the actual existing and correct API). To solve the consistency problem, when retrieving code snippets from external knowledge bases, use code-based queries instead of relying on natural language retrieval. With the generated rough code C r As the query content, relevant knowledge snippets are retrieved from the external knowledge base through similarity search. For example, compare accelerate.some_model() with all code lines in the knowledge base that contain accelerate API calls, and filter out code snippets with high similarity. Through retrieval, find the actual API call code snippet related to the model in the knowledge base, such as the code related to from accelerate import load_checkpoint_and_dispatch. In this process, use advanced similarity measurement algorithms to obtain the most matching code snippet k i , thereby reducing retrieval errors caused by the mismatch between natural language and code structure. The retrieval process can be represented by the formula , where k i represents the code snippet in the knowledge base, and V represents the most relevant code snippet retrieved according to the similarity measurement.

[0050] Step 3: The large model generates a knowledge-enhanced refined code snippet based on the given rough code, library requirements, version constraints, and retrieved knowledge snippets.

[0051] Input the rough code C r , library requirements R l , version constraints V c , and retrieved knowledge snippets V into the large model. The large model comprehensively analyzes the input information. According to the library requirements and version constraints, check the correctness of the API calls in the rough code, and use the retrieved knowledge snippets to supplement and correct the code. The large model combines these rich information to optimize the code in depth. The large model deeply analyzes the retrieved knowledge snippets V, extracts the correct API usage and code logic, and integrates them into the rough code C r , and corrects and perfects the API calls in it. At the same time, the large model according to the version constraints V c and library requirements R l, ensuring that the generated code meets the specific requirements of the project. If the project requires the use of a specific version of the library, and the usage of certain APIs in that version has changed, the large model will adjust the code accordingly to ensure that the code can run correctly in the environment of that version of the library. For example, if the retrieved knowledge fragment explicitly states that the correct callback function for accelerate in version 0.8.0 is init_empty_weights, the large model will modify init_weights in the rough code to init_empty_weights, and further refine other parts of the code, such as adding necessary parameter settings and error handling, etc. After this series of processing, the refined code fragment C f = f(C r , R l , V c , V).

[0052] This code not only improves the correctness of the application program interface (API) using external information, but also ensures better compatibility with production-level requirements, meeting the strict requirements of actual software development projects for code quality and performance.

[0053] The applicant of the present application has made a detailed description and explanation of the embodiments of the present application in combination with the drawings attached to the specification. However, those skilled in the art should understand that the above embodiments are only preferred embodiments of the present application, and the detailed description is only to help the reader better understand the spirit of the present application, and is not a limitation on the protection scope of the present application. On the contrary, any improvement or modification based on the spirit of the present application should fall within the protection scope of the present application.

Claims

1. A code generation method based on reasoning time extension, characterized in that: The method comprises the following steps: Case 1: No external information scenario: Step 1, generate an initial code draft with API calls, Step 2: The large model generates refined code with correct API calls based on the given rough code, library requirements, and version constraints, taking into account the impact of Python API version evolution on code migration. Case 2: Using external information and introducing rough code retrieval scenarios: Step 1: Crawl Python libraries from PyPI and GitHub, extract source code across versions, store metadata such as repository name, version, file path, and code in JSON format, and build an external knowledge base. Step 2: Generate a rough code snippet and use it as a query to retrieve related code snippets from the external knowledge base through similarity retrieval. In step 3, the large model generates knowledge-enhanced refined code snippets based on the given rough code, library requirements, version constraints, and retrieved knowledge snippets.

2. The code generation method based on inference time extension according to claim 1, characterized in that: In case 1, step 1 is as follows: given the missing code fragment C m and library requirements R l , the model generates a rough code snippet C r =f(C m ,R l ), the rough code C generated in this step r Meet the following structural requirements: The overall code framework conforms to the syntax specifications of the target programming language, such as Python's function definition structure and class declaration format; The key logic flow is complete, including the core code blocks required to solve the task, such as loops, conditional judgments and other control structures; The reserved API call locations match the task requirements, but the following potential problems are allowed: the API name may be incompatible with the target library version, such as using an outdated function name; the parameter type or number is inconsistent with the actual library interface; version-specific API changes, such as new parameters or deprecated fields, are not handled. The rough code serves as the basis for subsequent fine editing. Its core role is to provide an initial structural skeleton for complex code generation tasks, which is convenient for combining version constraints V in the second step. c Make targeted corrections.

3. The code generation method based on inference time extension according to claim 1, characterized in that: In case 1, step 2 is as follows: Given a rough code C r , library requirements R l , Version Constraint V c , the model generates the final code C through refined reasoning f =f(C r ,R l ,V c ), Refined reasoning includes the following: API correctness correction: replace API calls in the rough code that are incompatible with the target library version, verify the type and number of API parameters, and ensure consistency with the target library documentation; Structural enhancements: Incorporate containerization support code and insert parameter type range verification logic; Version compatibility adaptation: Generate version-compatible dependency declarations for API changes specific to the target library version to ensure that the code can be reproducibly run. Fine-tuned code C f Necessary modifications have been incorporated, resulting in significant improvements in API call accuracy, version compatibility, and deployment adaptability.

4. The code generation method based on inference time extension according to claim 1, characterized in that: In case 2, step 1 is as follows: The structured knowledge base for the retrieval-enhanced code generation is obtained, including: Data crawling: Batch obtain the historical version source code of the target Python library from the Python package index and GitHub code repository, covering the entire version chain from the initial version to the latest stable version; Metadata extraction: For each library version, the source code is parsed to extract the following information: basic metadata such as the library name, semantic version number, and file path; API definitions such as the complete signature, parameter descriptions, and return value types of functions / classes; and usage patterns of typical call snippets extracted from sample code or test cases. Structured storage: Organize the above information into knowledge base entries in JSON format; Index optimization: Establish a semantic index based on code snippets for the knowledge base, supporting fast retrieval through multiple dimensions such as function name, parameter type, and version number. The structured knowledge base ensures that in subsequent code generation, the model can retrieve version-specific API definitions and usage patterns through rough code.

5. The code generation method based on inference time extension according to claim 1, characterized in that: In case 2, step 2 is as follows: The process first generates a rough code snippet C from the model r , which replaces traditional natural language queries as structured query content and retrieves relevant knowledge fragments from external knowledge bases through semantic similarity search. The specific process is: Query generation: missing code snippets based on input C m and library requirements R l , generates rough C code that contains the core logic structure including placeholder API calls r ; Semantic retrieval: Using code semantic matching algorithms such as AST-based structural similarity calculation or Embedding vector cosine similarity, C r With the code snippet collection {k i } for matching, the calculation formula is: Among them, k i represents the code snippet with version information stored in the knowledge base. Sim(·) is the code semantic similarity measurement function. The higher the return value, the higher the matching degree. Result screening: Select the code fragment V with the highest similarity as the search result. This fragment must contain the code fragment with the highest similarity to C. r Matching API definitions, parameter usage patterns, or version-specific logic, The above steps improve the reliability and deployability of the code in a real production environment.

6. The code generation method based on inference time extension according to claim 1, characterized in that: In case 2, step 3 is as follows: Given a rough code C r , library requirements R l , Version Constraint V c And the most relevant code snippet V retrieved, the model will generate a fine-tuned code snippet C through knowledge fusion reasoning f =f(C r ,R l ,V c ), in this process, the optimization steps of external knowledge integration include: Enhance API correctness: Based on the version-specific API definitions contained in the retrieved code snippet V, correct incompatible function calls in the rough code and improve the actual application logic of API parameters based on the typical usage patterns in V; Adapting to production-level compatibility: Incorporating deployment-related configurations in code snippet V ensures that the generated code complies with cloud-native deployment standards and enhances the robustness of the generated code based on the error handling mechanisms included in V, such as exception capture logic and parameter validation code. Fusion of multi-source knowledge: Combined with the cross-library dependencies of API version evolution information stored in the knowledge base, code snippets that meet the requirements of multi-library collaboration are generated. Fine-tuned code C f Leverage external information to improve the correctness of your application programming interfaces (APIs) and ensure better compatibility with production-level requirements.

7. An electronic device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein: When the processor executes the program, the code generation method based on inference time extension as described in any one of claims 1 to 6 is implemented.

8. A computer-readable storage medium having computer instructions stored thereon, characterized in that: When the computer instruction is executed by a processor, a code generation method based on reasoning time extension according to any one of claims 1 to 6 is implemented.

Citation Information

Cited By

  • Optimization method, device and equipment for large language model oriented to extensive scene, storage medium and product

    CN121166656A