Code generation method and device, computer equipment and storage medium
By performing semantic analysis on code generation requests and using a pre-defined code knowledge graph for filtering and expansion, the semantic understanding bias and usability issues of general LLM in code generation are resolved, achieving high-quality code generation that aligns with business intent.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- PING AN TECH (SHENZHEN) CO LTD
- Filing Date
- 2026-01-20
- Publication Date
- 2026-05-05
AI Technical Summary
Existing generalized large language models (LLM) lack business semantic understanding specific to a project when generating code, resulting in semantic comprehension bias, poor usability, and the generation of irrelevant and noisy code snippets, which affects the functionality and architectural consistency of the code.
By performing semantic analysis on the code generation request, request semantic tags and keywords are generated. A pre-set code knowledge graph is used to filter and expand candidate code nodes, determine the target prompt information, and input it into a large language model to generate code.
It improves the semantic alignment and usability of code generation, ensures that the generated code conforms to business intent, reduces noisy code, and improves code quality and development efficiency.
Smart Images

Figure CN121979503A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of artificial intelligence technology, and more particularly to a code generation method, apparatus, computer equipment, and storage medium in the fields of fintech and healthcare. Background Technology
[0002] With the development of deep learning, code generation technology based on Large Language Models (LLMs) has been widely applied in software development across various fields. In the financial and insurance industry, LLMs are used to parse insurance terms or risk control rules described in natural language, automatically generating corresponding code logic and reducing human coding errors. In the healthcare industry, LLMs are used to parse medical terminology or clinical guidelines, generating reference code that includes data loading, model definition, and training loops, accelerating the development of clinical decision support systems. However, existing code generation technologies rely solely on general-purpose LLMs, which have some shortcomings when dealing with complex systems (such as core banking transaction systems and hospital information systems). General-purpose LLMs lack a business semantic understanding specific to the project, affecting the functionality of the generated code. For example, in a general context, "User" may refer to an ordinary user, but in a specific financial system, it may specifically refer to a "KYC-verified transaction entity." Code generated by general-purpose LLMs often fabricates non-existent method signatures or parameter lists, causing the generated code to fail to compile or contain security vulnerabilities, reducing the usability of the generated code. General-purpose LLM uses simple vector retrieval, which easily retrieves a large number of similar but irrelevant noisy code snippets, while omitting necessary context and affecting the architectural consistency of the generated code. Summary of the Invention
[0003] Therefore, it is necessary to provide a code generation method, apparatus, computer equipment, and storage medium to address the aforementioned technical problems, thereby resolving the issues of semantic comprehension bias and poor code usability in code generation based on general LLM.
[0004] A code generation method, comprising: Semantic analysis is performed on the code generation request to obtain request semantic tags and request keywords, and text embedding processing is performed on the code generation request to obtain request transformation vector; Find at least one candidate code node that matches the semantic tag of the request from the preset code knowledge graph; Based on the requested transformation vector, all the candidate code nodes are filtered to obtain reference code nodes; Based on the request keywords, perform node expansion processing on all the reference code nodes to obtain context nodes; The target prompt information is determined based on the code generation request, the reference code node, and the context node; The target prompt information is input into a preset large language model to obtain the target code corresponding to the code generation request.
[0005] A code generation apparatus, comprising: The request analysis module is used to perform semantic analysis on the code generation request to obtain request semantic tags and request keywords, and to perform text embedding processing on the code generation request to obtain a request transformation vector; The candidate node determination module is used to find at least one candidate code node that matches the request semantic tag from a preset code knowledge graph; The reference node determination module is used to filter all the candidate code nodes according to the request transformation vector to obtain reference code nodes; The extension processing module is used to perform node extension processing on all the reference code nodes according to the request keywords to obtain context nodes; The prompt information determination module is used to determine the target prompt information based on the code generation request, the reference code node, and the context node; The target code generation module is used to input the target prompt information into a preset large language model to obtain the target code corresponding to the code generation request.
[0006] A computer device includes a memory, a processor, and computer-readable instructions stored in the memory and executable on the processor, wherein the processor implements the code generation method described above when executing the computer-readable instructions.
[0007] A computer-readable storage medium storing computer-readable instructions that, when executed by one or more processors, cause the one or more processors to perform the code generation method described above.
[0008] In the aforementioned code generation method, apparatus, computer equipment, and storage medium, the code generation method performs semantic analysis on the code generation request to obtain request semantic tags and request keywords, and performs text embedding processing on the code generation request to obtain a request transformation vector; it then searches for at least one candidate code node matching the request semantic tags from a preset code knowledge graph; it filters all candidate code nodes based on the request transformation vector to obtain reference code nodes; it expands all reference code nodes based on the request keywords to obtain context nodes; it determines target prompt information based on the code generation request, reference code nodes, and context nodes; and it inputs the target prompt information into a preset large language model to obtain the target code corresponding to the code generation request. This invention obtains request semantic tags through semantic analysis, enabling accurate matching of user business intent during subsequent knowledge retrieval using a preset code knowledge graph, thus improving semantic alignment. This invention filters and expands candidate code nodes to generate target prompt information, providing accurate references for the large language model, improving the usability of the generated code. The target prompt information is compatible with multiple large language models, effectively improving code quality and development efficiency. Attached Figure Description
[0009] To more clearly illustrate the technical solutions of the embodiments of the present invention, the drawings used in the description of the embodiments of the present invention will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0010] Figure 1 This is a schematic diagram of an application environment for a code generation method according to an embodiment of the present invention; Figure 2 This is a flowchart illustrating a code generation method in one embodiment of the present invention; Figure 3 This is a schematic diagram of the structure of a code generation device in one embodiment of the present invention; Figure 4 This is a schematic diagram of a computer device according to an embodiment of the present invention. Detailed Implementation
[0011] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some, not all, of the embodiments of the present invention. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0012] The code generation method provided in this embodiment can be applied to, for example, Figure 1 In this application environment, the client communicates with the server. Clients include, but are not limited to, various personal computers, laptops, smartphones, tablets, and portable wearable devices. The server can be implemented using a standalone server or a server cluster consisting of multiple servers.
[0013] The code generation method described in this embodiment can be applied to the financial and insurance industry. Specifically, when developing an automated claims process, a claims knowledge graph is constructed in advance by associating medical diagnosis codes and insurance coverage with historical claims data. Based on the user's code generation request, the large language model can extract key information and map it to nodes in the claims knowledge graph, automatically generating the logic judgment code for the claims process.
[0014] The code generation method described in this embodiment can also be applied to the healthcare industry. Specifically, when developing an intelligent diagnostic and treatment assistance system, structured data such as diseases, symptoms, examination indicators, medications, and guidelines are integrated in advance using historical diagnostic and treatment data to construct a medical knowledge graph. Based on the user's input code generation request, the large language model can combine the medical knowledge graph to generate diagnostic suggestion code and automatically generate supporting logic code such as medication reminders and follow-up visit plans.
[0015] In one embodiment, such as Figure 2 As shown, a code generation method is provided, which can be applied to applications such as... Figure 1 The server-side component includes the following steps S10-S60.
[0016] S10. Perform semantic analysis on the code generation request to obtain request semantic tags and request keywords, and perform text embedding processing on the code generation request to obtain request transformation vector.
[0017] Understandably, users can input information through the client's display interface. The client then generates a code generation request based on this input and sends it to the server. The code generation request is the user's specific code requirements described in natural language. Upon receiving the request, the server performs semantic analysis to obtain request semantic tags and request keywords. Request semantic tags are identifying information in the code generation request's intent that characterizes specific needs in terms of business domain and technical architecture, including business domain request tags and technical architecture request tags. Request keywords refer to the specific requirements of the code application scenario within the code generation request. Furthermore, the server performs text embedding processing on the code generation request to obtain a request transformation vector. The request transformation vector is a numerical vector representation generated by converting the code generation requirements described in natural language using text embedding technology.
[0018] Specifically, suppose a developer inputs a code generation request from the client stating, "Write a method to asynchronously list a financial product, and perform risk control before listing." The server performs semantic analysis on the code generation request, obtaining request semantic tags and request keywords. The business domain request tag is "D_financial product," the technical architecture request tag is "T_asynchronous," and the request keyword is "risk control." Simultaneously, the server transforms the code generation request in real-time using a pre-trained text embedding model, obtaining a high-dimensional floating-point array. This transformed array is then used as the request transformation vector.
[0019] S20. Find at least one candidate code node that matches the semantic tag of the request from the preset code knowledge graph.
[0020] In essence, a pre-built code knowledge graph is a graph network constructed based on a graph structure to describe the internal logic, structure, and functional information of code. The pre-built code knowledge graph contains multiple code entity nodes, each with its own semantic label attributes. Candidate code nodes refer to code entity nodes in the pre-built code knowledge graph that meet the specific requirements of the code generation request in terms of business domain and technical architecture.
[0021] In one embodiment, step S20, before finding at least one candidate code node matching the request semantic tag from the preset code knowledge graph, includes: S201. Obtain multiple sets of historical source code, perform semantic analysis on each set of historical source code, and generate semantic tag annotations for each set of historical source code; S202. Perform dependency analysis on all the historical source codes and generate dependency description annotations for each of the historical source codes; S203. For each historical source code, extract the code entities and structural relationships of the historical source code; S204. Generate a preset code knowledge graph based on the code entities, structural relationships, semantic tag annotations, and dependency description annotations of all the historical source code. The preset code knowledge graph is established by creating nodes based on code entities, creating edges based on structural relationships, and generating node attribute vectors based on semantic tag annotations and dependency description annotations.
[0022] Understandably, before searching the pre-defined code knowledge graph, the server needs to first construct a pre-defined code knowledge graph based on historical source code. Historical source code is a set of code written in the past to implement specific functions. It can be source code downloaded from a code database, manually written during past application development, or generated using a large language model. The server performs semantic analysis on each set of historical source code, generating semantic tag annotations for each set. These annotations refer to the attribute information of the Application Programming Interface (API) in the historical source code regarding its business domain and technical architecture. Simultaneously, the server extracts the code entities and structural relationships from each set of historical source code. Code entities refer to the constituent objects of the code (such as classes and methods), and structural relationships refer to the interaction methods between code entities (such as calls and inheritance). Furthermore, the server performs dependency analysis on all historical source code, generating dependency description annotations for each set. Dependency description annotations describe the functional responsibilities of code segments commonly called across multiple sets of historical source code, such as the functional responsibilities of methods or functions called by a majority of code. The server represents all historical source code entities, structural relationships, semantic annotations, and dependency description annotations in a graph structure, generating a pre-defined code knowledge graph. In this pre-defined knowledge graph, code entities are nodes; for example, a "class" is a node, and a "method" is also a node. Structural relationships are edges, such as "method A [calls] method B". Semantic annotations and dependency description annotations are node attributes. Node attributes store the list of tags parsed from the semantic annotations, are configured with inverted indices for method and class names, and vector indices for the content of dependency description annotations.
[0023] This embodiment first extracts tags and annotations to label the code with business and architectural tags, and enhances the description of core dependencies. Then, it constructs a high-semantic-density code knowledge graph based on code entities, structural relationships, semantic tag annotations, and dependency description annotations. This improves the semantic understanding and query accuracy of the knowledge graph and helps to achieve high-quality code generation.
[0024] In one embodiment, step S201, namely, performing semantic analysis on each of the historical source codes to generate semantic tag annotations for each of the historical source codes, includes: S2011. Analyze the historical source code to identify the application programming interface code; S2012. Semantic analysis is performed on the application interface code using a preset prompt word template and a pre-trained semantic analysis model to obtain business domain tags and technical architecture tags. S2013. Generate semantic tag annotations for the historical source code based on the business domain tags and technical architecture tags.
[0025] Understandably, the server utilizes a pre-trained semantic analysis model and preset prompt word templates to perform semantic analysis of the application programming interface (API) in historical source code, considering both business domain and technical architecture. Semantic annotation tags derived from this analysis are then inserted into the historical source code. These semantic annotation tags are inserted into the source file in the form of programming language-specific metadata annotations. Semantic annotation tags include two dimensions: business domain tags and technical architecture tags. Business domain tags define the business boundaries of the code (e.g., "D_financial product shelf", "D_patient file creation"); technical architecture tags define the technical implementation mode of the code (e.g., "T_asynchronous execution", "T_distributed lock"). The pre-trained semantic analysis model is a pre-trained large language model designed to identify the intent regarding business domain and technical architecture in the API code. The preset prompt word templates contain task instructions, the context of the code, and structured output format requirements. On one hand, the preset prompt word templates decouple the business semantics and technical semantics of the code, forcing the model to analyze these two dimensions independently through instructions. On the other hand, the pre-set prompt word templates guide the pre-trained semantic analysis model to understand the business boundaries behind the code symbols (such as identifying that the code belongs to the "D_financial product shelf" domain), and the pre-set prompt word templates guide the pre-trained semantic analysis model to identify the key technical implementation patterns in the code (such as extracting the "T_asynchronous execution" feature), thus solving the problem of cross-language and cross-term retrieval and matching.
[0026] In addition, the server supports two semantic analysis modes: single-file precise mode and batch scanning mode. Single-file precise mode responds to a user-specified source code file path, performing semantic analysis and inserting semantic annotation tags only on that specific source code file. Batch scanning mode can traverse all source code files in a specified directory, performing semantic analysis and inserting semantic annotation tags in batches.
[0027] This embodiment, based on preset prompt word templates and a pre-trained semantic analysis model, can decouple and map features across different dimensions of code, improving the accuracy of semantic tag annotations. Semantic tag annotations help quickly locate corresponding code files and functions by searching for business domain tags and technical architecture tags, improving the accuracy and efficiency of code generation.
[0028] In one embodiment, step S202, namely, performing dependency analysis on all the historical source code and generating dependency description annotations for each of the historical source code, includes: S2021. Based on the abstract syntax tree, parse all the historical source code to obtain the call directed graph; S2022. Sort the in-degree values of each directed graph node in the called directed graph, and determine the first preset number of directed graph nodes with the highest in-degree values as core dependent nodes. S2023. The historical source code corresponding to each core dependency node is transformed by a preset dependency analysis model to obtain dependency function description and dependency example description, and dependency description annotation is generated based on the dependency function description and dependency example description.
[0029] Understandably, firstly, the server parses all historical source code based on an Abstract Syntax Tree (AST) to construct a method-level directed graph of calls. Then, the server calculates and sorts the in-degree (or PageRank) values of each directed graph node in the call graph; the N nodes with the highest values are selected as core dependency nodes. The first preset quantity, denoted by N, is a pre-defined value used to limit the number of core dependency nodes. It can be set to a default value or adjusted as needed, such as N being a positive integer greater than or equal to 5. Next, the server inputs the historical source code corresponding to the core dependency nodes and the context code of their respective classes into a preset dependency analysis model. This model generates natural language summaries and correct call code snippets using a few-shot prompting method, encapsulating the generated content as dependency description annotations. The preset dependency analysis model is a pre-trained neural network model used to parse call code snippets from historical source code and generate functional and instance descriptions. The dependency functional description refers to the natural language summary content generated by the preset dependency analysis model, and the dependency instance description refers to the correct call code snippets generated by the preset dependency analysis model. Each core dependency node corresponds to a dependency description annotation, which includes a description of the dependency's functionality and a description of the dependency's example.
[0030] This embodiment visually displays the dependencies between code snippets using a directed graph, and quickly locates frequently invoked core dependency nodes by combining in-degree sorting, reducing the time spent understanding complex code. Dependency description annotations facilitate the merging of frequently invoked code snippets, improving development efficiency.
[0031] In a specific embodiment, taking a typical financial transaction system written in Java as an example, the specific construction process of the preset code knowledge graph is illustrated. First, the server traverses the Controller and Service layer interfaces of the historical source code in the code repository. For each historical source code file, it constructs the following prompt words to input the LLM of the pre-trained semantic analysis model: "Please analyze the business logic and technical implementation of the following Java code. Please select the business domain tag from ['Account Management', 'Transfer Payment', 'Wealth Management Products'...] and the technical architecture tag from ['Synchronous', 'Asynchronous', 'Transaction', 'Cache'...]. Return it in the form of @JavaCodeTags annotation." The preset prompt word template can be designed according to task requirements; the above is just an example. After LLM processing, the code is automatically modified, for example, by inserting @JavaCodeTags(tags={"D_Financial Product Shelf", "T_Asynchronous Execution"}) and public void listProducts(...) { ...} in ProductService.java. Next, the server scans the abstract syntax tree of all historical source code, counts the method call frequency, constructs a directed call graph, and calculates the node centrality. Suppose the `RiskControlUtil.checkUser` method is found to be called 500 times, ranking first. The server then separately calls the default dependency analysis model's LLM for this method to generate enhanced dependency description annotations. These enhanced annotations are then updated in the utility class. @JavaCodeTags(tags={"D_Risk Control Core"}, / / Optional, additional business tags can be added) The description states that this function performs user-level risk control checks and returns a boolean value. It must be called before a transaction begins. example="boolean safe = RiskControlUtil.checkUser(userId, Context.get());") public static boolean checkUser(...) { ...} For regular APIs, annotations may only contain tags; for core dependency nodes, annotations are expanded to include description and example fields. Finally, the server uses a graph database (such as Neo4j) to construct a pre-defined code knowledge graph. This involves creating Class, Method, and Interface nodes as entity nodes. The list of tags parsed from the source code is stored as the node's business_tags and tech_tags attributes, while description and example are stored as the node's text attributes, generating node attribute vector embeddings. "business_tags" represents business domain tags, "tech_tags" represents technical architecture tags, "description" represents dependency function descriptions, and "example" represents dependency example descriptions. Structured relationships such as (:Method)-[:CALLS]->(:Method) and (:Class)-[:DEFINES]->(:Method) are established, with "CALLS" and "DEFINES" as edge type labels, representing call relationships and definition relationships, respectively. Create inverted indexes for method names and class names, and vector indexes for vector embeddings of descriptive text to support efficient retrieval and complete the construction of a pre-defined code knowledge graph.
[0032] In one embodiment, step S20, namely finding at least one candidate code node matching the request semantic tag from a preset code knowledge graph, includes: S205. The request semantic tag is compared one by one with the semantic tag annotations of all code entity nodes in the preset code knowledge graph, and the code entity nodes whose semantic tag annotations are consistent with the request semantic tag are determined as candidate code nodes.
[0033] Understandably, the server matches the request semantic tags with the semantic tag attributes of each code entity node in the pre-defined code knowledge graph, and identifies the matching code entity nodes as candidate code nodes. Specifically, suppose a developer inputs the requirement: "Write a method to asynchronously list financial products, and perform risk control before listing." The server analyzes and obtains the request semantic tags and request keywords. The business domain request tag is "D_financial products," the technical architecture request tag is "T_asynchronous," and the request keyword is "risk control." The server then executes a Cypher query in Neo4j, matching nodes whose business_tags contain "financial product shelf" and tech_tags contain "asynchronous execution," and identifies these matching nodes as candidate code nodes.
[0034] This embodiment compares the request semantic tags with the semantic tag annotations in the code knowledge graph, which can quickly locate the code entity node that semantically matches the current requirement. It can filter out a large amount of irrelevant code, which helps to accurately match the user's business intent and reduce the possibility of business matching deviation.
[0035] S30. Filter all the candidate code nodes according to the request transformation vector to obtain the reference code node.
[0036] Understandably, the server performs a similarity analysis between the request transformation vector and the node attribute vectors of the candidate code nodes. Based on the similarity analysis results, all candidate code nodes are filtered to obtain reference code nodes. Reference code nodes refer to code entity nodes in the pre-defined code knowledge graph that meet the specific needs of the code generation request in terms of business domain and technical architecture, as well as specific needs in terms of call dependencies.
[0037] In one embodiment, step S30, namely, filtering all the candidate code nodes according to the request transformation vector to obtain reference code nodes, includes: S301. Perform similarity analysis on the node attribute vector of each candidate code node and the request conversion vector to obtain the candidate similarity value of each candidate code node. S302. Sort all the candidate code nodes according to the candidate similarity value, and select the second preset number of candidate code nodes with the highest candidate similarity value as reference code nodes.
[0038] Understandably, for each candidate code node, the server calculates the similarity between the node attribute vector and the request transformation vector to obtain the candidate similarity value for that candidate code node. The node attribute vector refers to the attribute vector corresponding to the dependency function description and the dependency example description. The candidate similarity value is a quantified value of the semantic matching degree between the node attribute vector and the request transformation vector. Similarity calculation can be performed using cosine similarity or Euclidean distance algorithms. The server sorts all candidate code nodes according to the candidate similarity values and selects the second preset number of candidate code nodes with the highest candidate similarity values as reference code nodes. This allows for precise identification of code entity nodes that are closest to the user's intent in terms of "functional semantics." The second preset number, denoted by K, is a pre-defined value used to limit the number of reference code nodes. It can be set to a default value or adjusted as needed, such as K being a positive integer greater than or equal to 3.
[0039] Specifically, suppose a developer inputs the requirement: "Write a method to asynchronously list financial products, and perform risk control before listing." The server executes a Cypher query in Neo4j, matching nodes whose business_tags contain "financial product shelf" and tech_tags contain "asynchronous execution," identifying these nodes as candidate code nodes. Further, the server retrieves the attribute vectors corresponding to the dependency function description and dependency example description (embedded vectors from description and example) from the node attribute vectors of each candidate code node, calculates the similarity between the embedding vectors of description and example and the request transformation vector, and finds the reference code node.
[0040] This embodiment sorts all candidate code nodes by calculating candidate similarity values and selects the reference code nodes with the highest similarity. This can accurately identify the code entity nodes that are closest to the user's intent in terms of "functional semantics." This embodiment compares similarity based on the dependency function descriptions and dependency example descriptions attached to the node attribute vectors, providing accurate references for subsequent LLM operations, significantly reducing problems such as illusions and core dependency call errors, and improving the usability and security of the generated code.
[0041] S40. Perform node expansion processing on all the reference code nodes according to the request keywords to obtain context nodes.
[0042] Understandably, the server retrieves code entity nodes that have dependencies on various reference code nodes, performs node expansion processing, and filters the expanded code entity nodes based on the request keywords to obtain context nodes. Context nodes refer to code entity nodes in the pre-defined code knowledge graph that meet the specific needs of the code generation request in terms of business domain and technical architecture, specific needs in terms of call dependencies, and keyword requirements.
[0043] In one embodiment, step S40, namely, performing node expansion processing on all the reference code nodes according to the request keyword to obtain context nodes, includes: S401. For each reference code node, in the preset code knowledge graph, with the reference code node as the center, traverse along the call relationship edge and the inheritance relationship edge to obtain the traversal extended subgraph. S402. Filter the code entity nodes in the traversal extended subgraph according to the request keywords to obtain context nodes.
[0044] Understandably, in a code knowledge graph, a single code entity node (e.g., function "func A") often only contains its own code snippet. Looking at a node in isolation may not reveal the complete business meaning of the code. The server traverses along call and inheritance edges to complete the structured dependencies and reconstruct the code execution logic. For example, traversing along "CALLS" edges can identify which function "func A" calls, or which function calls "func A". Identifying the upstream and downstream connections of "func A" is crucial to reconstructing the complete "business execution flow" chain. The scope and number of traversals can be adjusted as needed, for example, traversing within a limited range (1 to 2 hops), as full graph traversal is computationally intensive and noisy. "1 to 2 hops" is an empirical value, primarily used to obtain the most relevant local information (i.e., directly related upstream and downstream components), ensuring sufficient information while avoiding the introduction of irrelevant global code. Traversing the extended subgraph refers to the resulting graph network composed of reference code nodes and code entity nodes that have dependencies on the reference code nodes. The traversal extension subgraph is a local network within the predefined code knowledge graph that includes reference code nodes, "structured neighbors," and "semantic association points." The server matches the semantic tag annotations and dependency description annotations of each code entity node in the traversal extension subgraph based on the request keywords, identifying code entity nodes whose semantic tag annotations and dependency description annotations contain the request keywords as context nodes.
[0045] Specifically, suppose a developer inputs the requirement: "Write a method to asynchronously list financial products, and perform risk control before listing." The server executes a Cypher query in Neo4j, matching nodes whose business_tags contain "financial product shelf" and tech_tags contain "asynchronous execution," identifying these nodes as candidate code nodes. Further, the server retrieves the attribute vectors corresponding to the dependency function description and dependency example description (embedded vectors from description and example) from the node attribute vectors of each candidate code node, and calculates the similarity between the embedding vectors of description and example and the request transformation vector to find reference code nodes. Next, starting from the reference code node in the preset code knowledge graph, it performs a 1-2 hop traversal along relationship edges such as CALLS, while simultaneously filtering based on the keyword "risk control," identifying the highly relevant core dependency node RiskControlUtil.checkUser, which is then determined as the context node.
[0046] This embodiment maximizes the utilization of the pre-defined code knowledge graph through a three-level hybrid retrieval strategy of "tag filtering, vector matching, and graph traversal expansion". Tag filtering ensures the business relevance of the prompts from the large language model, vector matching ensures the most semantically relevant information, and graph traversal expansion ensures the integrity of the context. This allows the knowledge graph-based retrieval to preserve the structural relationships between codes, and the subsequently generated code conforms to the project's existing architectural style and coding standards, making it easy to pass reviews, tests, and maintenance.
[0047] S50. Determine the target prompt information based on the code generation request, the reference code node, and the context node.
[0048] Understandably, the server determines reference code snippets based on reference code nodes. These reference code snippets are code entities selected through label filtering and vector matching, containing structured information such as the method's signature, parameter list, and return value; they are also known as the "seed method's code structure." The server determines reference dependency code snippets for core dependency nodes associated with the reference code nodes based on context nodes. These reference dependency code snippets are nodes found through graph traversal expansion; they contain natural language descriptions of functional responsibilities and standard calling examples, helping the large language model understand the specific purpose and calling methods of these dependency methods; they are also known as "descriptions and examples of core dependency methods." The server then structurally represents the code generation request, reference code snippets, and reference dependency code snippets, generating target hint information. Target hint information refers to reference information used to guide the large language model to accurately understand the code generation request and generate code that meets the requirements. Reference code snippets and reference dependency code snippets not only contain abstract "entities and relationships" but also the specific code definitions and implementation details corresponding to these entities; specifically, they are a filtered set of code references with structured and defined information. The target hints can guide the large language model: "Now we have these ready-made components (entities), they are combined in this way (relationships), and the specific function definitions are like this (code snippets). Please reuse them when generating new code." S60. Input the target prompt information into a preset large language model to obtain the target code corresponding to the code generation request.
[0049] To be understandable and specific, suppose a developer inputs the requirement: "Write a method to asynchronously list financial products, and perform risk control before listing." The target prompt message received by the LLM will not only include similar code but also the message "Note: Please refer to the RiskControlUtil.checkUser example for risk control calls." The final code output by the LLM is not only logically sound but also correctly inserts the RiskControlUtil.checkUser call code at the beginning of the method, fully conforming to the specifications. Furthermore, the programming languages used in the final LLM output code include, but are not limited to, Java, Python, and C.
[0050] This embodiment performs semantic analysis on the code generation request to obtain request semantic tags and request keywords, and performs text embedding processing on the code generation request to obtain a request transformation vector. It then searches for at least one candidate code node matching the request semantic tags from a preset code knowledge graph. Based on the request transformation vector, all candidate code nodes are filtered to obtain reference code nodes. Based on the request keywords, all reference code nodes are expanded to obtain context nodes. Based on the code generation request, reference code nodes, and context nodes, target prompt information is determined. This target prompt information is input into a preset large language model to obtain the target code corresponding to the code generation request. This embodiment obtains request semantic tags through semantic analysis, enabling accurate matching of the user's business intent when subsequently using the preset code knowledge graph for knowledge retrieval, thus improving semantic alignment. This embodiment filters and expands candidate code nodes to generate target prompt information, which is compatible with multiple large language models, effectively improving code quality and development efficiency, and enhancing the usability and security of the generated code.
[0051] The code generation method of this invention can be deployed on a standalone service or integrated development environment (IDE) plugin, including an automated annotation module, a core dependency analysis module, a graph management module, and a code generation module. The automated annotation module embeds a prompt word template manager, responsible for calling the LLM to perform AST parsing and annotation insertion on the source code. The core dependency analysis module includes a graph computation engine for constructing a call graph, calculating node centrality, and identifying the Top-N core dependency nodes. The graph management module is responsible for reading and writing the graph database, index maintenance, entity / relation extraction, and vectorization processing. The code generation service module serves as the front-end interactive entry point, receiving user commands, executing a hybrid retrieval strategy, assembling the context, calling the LLM to generate code, and finally displaying the results.
[0052] It should be understood that the sequence number of each step in the above embodiments does not imply the order of execution. The execution order of each process should be determined by its function and internal logic, and should not constitute any limitation on the implementation process of the embodiments of the present invention.
[0053] In one embodiment, a code generation apparatus is provided, which corresponds one-to-one with the code generation methods described in the above embodiments. For example... Figure 3 As shown, the code generation device includes a request analysis module 10, a candidate node determination module 20, a reference node determination module 30, an extension processing module 40, a prompt information determination module 50, and a target code generation module 60. Detailed descriptions of each functional module are as follows: The request analysis module 10 is used to perform semantic analysis on the code generation request to obtain request semantic tags and request keywords, and to perform text embedding processing on the code generation request to obtain a request transformation vector; The candidate node determination module 20 is used to find at least one candidate code node that matches the request semantic tag from a preset code knowledge graph; The reference node determination module 30 is used to filter all the candidate code nodes according to the request transformation vector to obtain reference code nodes; The extension processing module 40 is used to perform node extension processing on all the reference code nodes according to the request keywords to obtain context nodes; The prompt information determination module 50 is used to determine the target prompt information based on the code generation request, the reference code node, and the context node; The target code generation module 60 is used to input the target prompt information into a preset large language model to obtain the target code corresponding to the code generation request.
[0054] In one embodiment, the candidate node determination module 20 includes: A semantic analysis unit is used to acquire multiple sets of historical source code, perform semantic analysis on each set of historical source code, and generate semantic tag annotations for each set of historical source code. The dependency analysis unit is used to perform dependency analysis on all the historical source code and generate dependency description annotations for each of the historical source code. The information extraction unit is used to extract the code entities and structural relationships of each historical source code. The knowledge graph generation unit is used to generate a preset code knowledge graph based on the code entities, structural relationships, semantic tag annotations, and dependency description annotations of all the historical source code. The preset code knowledge graph is established by creating nodes based on code entities, creating edges based on structural relationships, and generating node attribute vectors based on semantic tag annotations and dependency description annotations.
[0055] In one embodiment, the candidate node determination module 20 further includes: The interface code recognition unit is used to parse the historical source code and identify the application interface code; The tag analysis unit is used to perform semantic analysis on the application interface code using a preset prompt word template and a pre-trained semantic analysis model to obtain business domain tags and technical architecture tags. The semantic tag annotation generation unit is used to generate semantic tag annotations for the historical source code based on the business domain tags and technical architecture tags.
[0056] In one embodiment, the candidate node determination module 20 further includes: The directed graph generation unit is invoked to parse all the aforementioned historical source code based on the abstract syntax tree, thereby obtaining the call directed graph; The core dependency node determination unit is used to sort the in-degree values of each directed graph node in the called directed graph, and determine the first preset number of directed graph nodes with the highest in-degree values as core dependency nodes. The dependency description annotation generation unit is used to transform the historical source code corresponding to each core dependency node through a preset dependency analysis model to obtain dependency function descriptions and dependency example descriptions, and generate dependency description annotations for the historical source code based on the dependency function descriptions and dependency example descriptions.
[0057] In one embodiment, the candidate node determination module 20 further includes: The tag comparison unit is used to compare the request semantic tag with the semantic tag annotations of all code entity nodes in the preset code knowledge graph one by one, and determine the code entity nodes whose semantic tag annotations are consistent with the request semantic tag as candidate code nodes.
[0058] In one embodiment, the reference node determination module 30 includes: The similarity analysis unit is used to perform similarity analysis on the node attribute vector of each candidate code node and the request conversion vector to obtain the candidate similarity value of each candidate code node. The reference code node determination unit is used to sort all the candidate code nodes according to the candidate similarity value, and select the second preset number of candidate code nodes with the highest candidate similarity value as reference code nodes.
[0059] In one embodiment, the extended processing module 40 includes: The traversal unit is used to traverse the preset code knowledge graph for each reference code node, taking the reference code node as the center and along the call relationship edge and the inheritance relationship edge to obtain the traversal extension subgraph. The context node determination unit is used to filter the code entity nodes in the traversal extended subgraph according to the request keywords to obtain the context nodes.
[0060] Specific limitations regarding the code generation device can be found in the limitations regarding the code generation method above, and will not be repeated here. Each module in the aforementioned code generation device can be implemented entirely or partially through software, hardware, or a combination thereof. These modules can be embedded in hardware or independently of the processor in the computer device, or stored in software in the memory of the computer device, so that the processor can call and execute the operations corresponding to each module.
[0061] In one embodiment, a computer device is provided, which may be a server, and its internal structure diagram may be as follows: Figure 4 As shown, the computer device includes a processor, memory, network interface, and database connected via a system bus. The processor provides computing and control capabilities. The memory includes a readable storage medium and internal memory. The readable storage medium stores an operating system, computer-readable instructions, and a database. The internal memory provides an environment for the operation of the operating system and computer-readable instructions in the readable storage medium. The database stores data related to the code generation method. The network interface communicates with external terminals via a network connection. When the computer-readable instructions are executed by the processor, they implement a code generation method. The readable storage medium provided in this embodiment includes both non-volatile and volatile readable storage media.
[0062] In one embodiment, a computer device is provided, including a memory, a processor, and computer-readable instructions stored in the memory and executable on the processor, wherein the processor performs the following steps when executing the computer-readable instructions: Semantic analysis is performed on the code generation request to obtain request semantic tags and request keywords, and text embedding processing is performed on the code generation request to obtain request transformation vector; Find at least one candidate code node that matches the semantic tag of the request from the preset code knowledge graph; Based on the requested transformation vector, all the candidate code nodes are filtered to obtain reference code nodes; Based on the request keywords, perform node expansion processing on all the reference code nodes to obtain context nodes; The target prompt information is determined based on the code generation request, the reference code node, and the context node; The target prompt information is input into a preset large language model to obtain the target code corresponding to the code generation request.
[0063] In one embodiment, one or more computer-readable storage media storing computer-readable instructions are provided. The readable storage media provided in this embodiment include non-volatile readable storage media and volatile readable storage media. The readable storage media stores computer-readable instructions, which, when executed by one or more processors, perform the following steps: Semantic analysis is performed on the code generation request to obtain request semantic tags and request keywords, and text embedding processing is performed on the code generation request to obtain request transformation vector; Find at least one candidate code node that matches the semantic tag of the request from the preset code knowledge graph; Based on the requested transformation vector, all the candidate code nodes are filtered to obtain reference code nodes; Based on the request keywords, perform node expansion processing on all the reference code nodes to obtain context nodes; The target prompt information is determined based on the code generation request, the reference code node, and the context node; The target prompt information is input into a preset large language model to obtain the target code corresponding to the code generation request.
[0064] Those skilled in the art will understand that all or part of the processes in the above embodiments can be implemented by instructing related hardware with computer-readable instructions. These computer-readable instructions can be stored in a non-volatile readable storage medium or a volatile readable storage medium. When executed, these computer-readable instructions can include the processes of the embodiments of the above methods. Any references to memory, storage, databases, or other media used in the embodiments provided by this invention can include non-volatile and / or volatile memory. Non-volatile memory may include read-only memory (ROM), programmable ROM (PROM), electrically programmable ROM (EPROM), electrically erasable programmable ROM (EEPROM), or flash memory. Volatile memory may include random access memory (RAM) or external cache memory. By way of illustration and not limitation, RAM is available in a variety of forms, such as static RAM (SRAM), dynamic RAM (DRAM), synchronous DRAM (SDRAM), dual data rate SDRAM (DDRSDRAM), enhanced SDRAM (ESDRAM), synchronous link DRAM (SLDRAM), RAMbus direct RAM (RDRAM), direct memory bus dynamic RAM (DRDRAM), and memory bus dynamic RAM (RDRAM), etc.
[0065] Those skilled in the art will clearly understand that, for the sake of convenience and brevity, the above-described division of functional units and modules is used as an example. In practical applications, the above functions can be assigned to different functional units and modules as needed, that is, the internal structure of the device can be divided into different functional units or modules to complete all or part of the functions described above.
[0066] The software tools or components not belonging to this company that appear in the embodiments of this application are merely illustrative examples and do not represent actual use. The above-described embodiments are only used to illustrate the technical solutions of the present invention, and are not intended to limit it; although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features; and these modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of the present invention, and should all be included within the protection scope of the present invention.
Claims
1. A code generation method, characterized in that, include: Semantic analysis is performed on the code generation request to obtain request semantic tags and request keywords, and text embedding processing is performed on the code generation request to obtain request transformation vector; Find at least one candidate code node that matches the semantic tag of the request from the preset code knowledge graph; Based on the requested transformation vector, all the candidate code nodes are filtered to obtain reference code nodes; Based on the request keywords, perform node expansion processing on all the reference code nodes to obtain context nodes; The target prompt information is determined based on the code generation request, the reference code node, and the context node; The target prompt information is input into a preset large language model to obtain the target code corresponding to the code generation request.
2. The code generation method as described in claim 1, characterized in that, Before searching for at least one candidate code node that matches the request semantic tag from the preset code knowledge graph, the process includes: Obtain multiple sets of historical source code, perform semantic analysis on each set of historical source code, and generate semantic tag annotations for each set of historical source code; Perform dependency analysis on all the historical source codes and generate dependency description annotations for each of the historical source codes; For each historical source code, extract the code entities and structural relationships of the historical source code; Based on the code entities, structural relationships, semantic tag annotations, and dependency description annotations of all the historical source code, a preset code knowledge graph is generated. The preset code knowledge graph is established by creating nodes based on code entities, creating edges based on structural relationships, and generating node attribute vectors based on semantic tag annotations and dependency description annotations.
3. The code generation method as described in claim 2, characterized in that, The step of performing semantic analysis on each of the historical source codes to generate semantic tag annotations for each of the historical source codes includes: The historical source code was parsed to identify the application programming interface (API) code; The application interface code is semantically analyzed using a preset prompt word template and a pre-trained semantic analysis model to obtain business domain tags and technical architecture tags. Based on the business domain tags and technical architecture tags, semantic tag annotations are generated for the historical source code.
4. The code generation method as described in claim 2, characterized in that, The step of performing dependency analysis on all the historical source code and generating dependency description annotations for each of the historical source code includes: Based on the abstract syntax tree, all the aforementioned historical source code is parsed to obtain the call directed graph; The in-degree values of each directed graph node in the called directed graph are sorted, and the first preset number of directed graph nodes with the highest in-degree values are determined as core dependent nodes. By using a preset dependency analysis model, the historical source code corresponding to each core dependency node is transformed to obtain dependency function descriptions and dependency example descriptions. Based on the dependency function descriptions and dependency example descriptions, dependency description annotations for the historical source code are generated.
5. The code generation method as described in claim 1, characterized in that, The step of finding at least one candidate code node that matches the request semantic tag from a preset code knowledge graph includes: The request semantic tag is compared one by one with the semantic tag annotations of all code entity nodes in the preset code knowledge graph, and the code entity nodes whose semantic tag annotations are consistent with the request semantic tag are determined as candidate code nodes.
6. The code generation method as described in claim 1, characterized in that, The step of filtering all the candidate code nodes according to the request transformation vector to obtain reference code nodes includes: A similarity analysis is performed on the node attribute vector of each candidate code node and the request conversion vector to obtain the candidate similarity value of each candidate code node. All candidate code nodes are sorted according to the candidate similarity value, and a second preset number of candidate code nodes with the highest candidate similarity value are selected as reference code nodes.
7. The code generation method as described in claim 1, characterized in that, The step of expanding all the reference code nodes according to the request keywords to obtain context nodes includes: For each of the aforementioned reference code nodes, the preset code knowledge graph is traversed along the call relationship edges and inheritance relationship edges with the reference code node as the center to obtain a traversal extended subgraph. The code entity nodes in the traversed extended subgraph are filtered according to the requested keywords to obtain the context nodes.
8. A code generation device, characterized in that, include: The request analysis module is used to perform semantic analysis on the code generation request to obtain request semantic tags and request keywords, and to perform text embedding processing on the code generation request to obtain a request transformation vector; The candidate node determination module is used to find at least one candidate code node that matches the request semantic tag from a preset code knowledge graph; The reference node determination module is used to filter all the candidate code nodes according to the request transformation vector to obtain reference code nodes; The extension processing module is used to perform node extension processing on all the reference code nodes according to the request keywords to obtain context nodes; The prompt information determination module is used to determine the target prompt information based on the code generation request, the reference code node, and the context node; The target code generation module is used to input the target prompt information into a preset large language model to obtain the target code corresponding to the code generation request.
9. A computer device comprising a memory, a processor, and computer-readable instructions stored in the memory and executable on the processor, characterized in that, When the processor executes the computer-readable instructions, it implements the code generation method as described in any one of claims 1 to 7.
10. A computer-readable storage medium storing computer-readable instructions, characterized in that, When the computer-readable instructions are executed by one or more processors, the one or more processors cause the code generation method as described in any one of claims 1 to 7 to be performed.
Citation Information
Cited By
Striped tube simulation macro script generation method based on knowledge graph and related products
CN122308805A