Behavior tree code automatic generation method based on large language model

By using a large language model and structured prompt design, behavior tree code is automatically generated, solving the problems of low efficiency and high error rate in existing technologies. This achieves efficient and reliable code generation, adapting to task planning in complex scenarios.

CN120909573APending Publication Date: 2025-11-07XIDIAN UNIV

Patent Information

Application Number
CN202511021557.8
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-07-24
Publication Date
2025-11-07

AI Technical Summary

Technical Problem

Existing technologies are inefficient in behavior tree code generation, prone to introducing errors, and lack versatility and flexibility in complex or variable scenarios, making it difficult to adapt to the diverse and complex behavior tree design requirements.

Method used

By employing a large language model combined with structured prompt design and fine-tuning methods, behavior tree code is generated by parsing XML files and user input, and then displayed and modified in a visual interface to ensure the security and accuracy of the code.

Benefits of technology

It achieves automated generation of behavior tree code, improving generation efficiency and code quality, meeting the task planning needs in complex scenarios, and reducing development cycle and error rate.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120909573A_ABST
    Figure CN120909573A_ABST
Patent Text Reader

Abstract

The invention discloses a behavior tree code automatic generation method based on a large language model. The method comprises the following steps: 1, acquiring a behavior tree model of an XML file format defined by a user and prompt information input by the user; 2, analyzing the obtained XML file, and providing a generation rule of a behavior tree code; step 3; the analyzed XML file and prompt information input by a user are combined with a behavior tree code generation rule, and a task specific prompt is generated; 4, combining the task specific prompt with the general code generation prompt to generate a complete prompt; 5, a proper LLM is selected, complete prompt information is input, and the LLM generates codes according to prompts; 6, running the generated code in a safe environment to ensure the safety of the code and the correctness of an output format; and 7, displaying an execution result on a visual interface, auditing the result by a user, and modifying a generated code. The method has the characteristics of high universality, high flexibility and high interpretability.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The application belongs to the technical field of artificial intelligence, and particularly relates to a behavior tree code automatic generation method based on a large language model. BACKGROUND

[0002] In related technologies, a behavior tree has a significant advantage in task planning process, and can effectively promote the implementation progress of a task. According to situation awareness information, the behavior tree can guide an autonomous system to make a decision, so that more efficient and more accurate task execution can be realized in a complex and changeable battlefield environment. The behavior tree provides a framework through the structuring of a task and a decision process, so that the autonomous system has stronger adaptability and response capability in a dynamic and unpredictable environment.

[0003] As shown in Figure 1 , a behavior tree (BT) is a tree structure used for modeling a decision process, has a definite root node and multiple branches, and the number of child nodes of each node can be flexibly changed. The behavior tree (BT) modeling can be expressed as a binary tuple:

[0004] BT=<V,E>

[0005] A node set V: contains multiple sub-sets:

[0006] A: an action node set, representing a specific operation to be executed.

[0007] C: a condition node set, used for evaluating a logical condition.

[0008] N: a logic node set (such as sequence, selection).

[0009] τ: a root node set.

[0010] Among them, the action node and the condition node are leaf nodes, and the logic node is a non-leaf node, used to build the hierarchical logic of the behavior tree.

[0011] An edge set E: an edge set describes the directed connection relationship between nodes.

[0012] v i ,v j ∈V,v i is the parent node of v j , and v j is the child node of v i

[0013] ​In the decision-making process, when it is necessary to determine the specific behavior that an entity should perform, the behavior tree searches the nodes V in the tree from the root node τ top-down according to a series of conditions, and finally finds and determines the behavior to be performed at the leaf node. This process can effectively organize and manage complex decision logic.

[0014] In the prior art, the behavior tree open source library is BehaviorTree.CPP, which is written in C++. The logic of the behavior tree can be loaded in the form of a configuration file by an XML file, and user-defined leaf nodes can also be dynamically loaded, which has considerable flexibility, and a graphical editing tool Groot is provided.

[0015] Through comprehensive analysis of the development status of this technical field, the following problems exist in the use of behavior trees (BT) in task planning processes: R&D engineers need to design and develop C++ code for loading behavior tree XML files, while implementing specific task execution logic. However, the current development mode usually relies on manually writing and editing C++ files. This process not only requires engineers to have a deep understanding of the structure and function of the behavior tree, but also requires a lot of time and effort to complete complex code writing and debugging. Therefore, this manual development method is inefficient, prone to errors, and significantly increases the cost of the development cycle.

[0016] Prior art one, patent CN106959850A, proposes a template-based behavior tree code generation method. This method pre-designs code templates suitable for specific programming languages and behavior tree frameworks, and the core is to accurately fill the structure and parameters of the behavior tree into the template to achieve the purpose of code generation. For example, for a specific behavior tree node type, such as a conditional judgment node, the template has set up a general architecture part containing node name, type, input and output parameters. Only the specific expression of the judgment condition, the involved variables and other parameters need to be filled in according to the logic requirements of the specific behavior tree, and the corresponding code fragment can be generated. This way can improve the code generation efficiency by reusing templates when dealing with some behavior tree generation tasks with similar structures, and the generated code structure is relatively regular and follows the established template specifications.

[0017] Prior art two, patent with publication number CN117472342A, proposes a behavior tree code automatic generation method based on front-end data model analysis and template insertion. The method enables users to construct a vehicle behavior tree graph structure through a visual interface, and the system converts the structure into a standardized front-end data model (such as JSON or XML). Based on the preset conversion rules and code templates, the system automatically generates the corresponding XML configuration file and C++ code implementation file for the vehicle behavior tree. The entire process does not rely on user manual code writing, and only requires configuring behavior logic to complete code generation. This method effectively improves the efficiency of vehicle behavior tree development, reduces the requirement for engineers to master the underlying programming framework, and has strong practicality and operational convenience.

[0018] Through the above analysis, the problems and defects of the prior art method are: although the efficiency is acceptable in specific scenarios, its dependence on preset templates and conversion rules limits its versatility and expandability. Once the behavior tree structure or logic requirements exceed the support range of existing templates, the automatic generation process will not meet the requirements, and manual intervention is required for template expansion and code adjustment. In addition, this method does not have the ability to learn structure logic from historical data, making it difficult to adapt to variable and complex behavior tree design requirements, and there is still room for improvement in flexibility and intelligence. SUMMARY

[0019] In order to overcome the deficiencies of the above prior art, the purpose of the present application is to provide a behavior tree code automatic generation method based on a large language model, which has the characteristics of strong versatility, high flexibility, and high interpretability.

[0020] In order to achieve the above purpose, the technical solution adopted by the present application is:

[0021] A behavior tree code automatic generation method based on a large language model, comprising the following steps:

[0022] Step 1: Obtain the behavior tree model in XML file format defined by the user and the prompt information input by the user;

[0023] Step 2: Parse the obtained XML file and provide the generation rules of the behavior tree code;

[0024] Step 3: Combine the parsed XML file and the user input prompt information with the generation rules of the behavior tree code to generate task-specific prompts to ensure that the LLM understands the context of the query;

[0025] Step 4: Combine the task-specific prompts with the general code generation prompts to generate a complete prompt to guide the LLM to generate code that responds to user queries;

[0026] Step five: select the appropriate LLM, input the complete prompt information, and the LLM generates code according to the prompt;

[0027] Step six: run the generated code in a secure environment to ensure the security of the code and the correctness of the output format;

[0028] Step seven: display the execution results on the visualization interface, and the user reviews the results and modifies the generated code.

[0029] In step one, the user drags each node through the graphical interface Groot tool and connects each node according to the logic to build a complete behavior tree model. After construction, the system saves the behavior tree model as an XML file for further processing and code generation.

[0030] The prompt information input by the user includes three parts: user request, behavior tree structure, and node description.

[0031] The user request part describes the action the user wants the model to perform, for example, the user inputs "Please generate the corresponding executable C++ code file (including the main code, node definition code, node definition library, and the corresponding cmake compilation file) according to the following behavior tree XML file, combined with BehaviorTree.CPP";

[0032] The behavior tree structure part inputs the XML file constructed by the user;

[0033] The node description part lists the various nodes in the behavior tree and their characteristics, including the relevant information of sequential nodes, fallback nodes, action nodes, and condition nodes.

[0034] In step two, the input behavior tree structure part XML file is parsed, and the node number, node type, node description, and node relationship are extracted in combination with the node description part. According to the parsing result, each node is characterized by four dimensions: node ID, node type, node location, and node description. Example: {"Node ID":"x","node type":"x","node location":"x,y","node description":"xxxxx"}. According to the node description, the prompt code is generated.

[0035] Example: "This conditional node called 'IsEnemyInRange', which receives the field of view data of the current character and the location information of the surrounding enemy units as input, and outputs a Boolean value to determine whether the enemy is within attack range."

[0036] The behavior tree execution code includes behavior tree main code, custom node code, and custom node library code.

[0037] The behavior tree main code is responsible for loading behavior tree configurations, initializing the behavior tree factory, registering nodes, executing the behavior tree, and handling logs and state tracking. The writing rules are summarized as follows: ① Load the definition of the behavior tree from an XML file or other configuration source; ② Create an instance of BehaviorTreeFactory to generate and manage behavior tree nodes; ③ Register all custom nodes using the BT_REGISTER_NODES macro; ④ Call the tickRoot method to execute the behavior tree; ⑤ Configure and use loggers (such as StdCoutLogger, FileLogger, etc.) to track the state changes of the behavior tree.

[0038] Custom node code defines specific behaviors and conditional judgments in the behavior tree. The writing rules are summarized as follows:

[0039] ① Define the interface for each custom node, usually a function that returns NodeStatus; ② Implement specific logic according to the function of the node, including conditional judgment and behavior execution; ③ Register custom nodes in the RegisterNodes function to the behavior tree factory; ④ Handle input and output: define and use ports to receive input and provide output, interact with the blackboard to share data.

[0040] Custom node library code is responsible for defining namespaces, declaring related functions, and facilitating subsequent code writing and mutual calling.

[0041] The interaction in step three with the LLM involves providing it with "prompts", which are natural language instructions that users input as part of task-specific prompts to provide context and guide the LLM in generating text responses; effective prompts can provide sufficient and useful parameters for the large model to perform tasks and generate reliable and effective responses, avoiding the generation of illusions. Prompt generation can be divided into two aspects: demand prompts for specific fields and comprehensive prompts for general procedures.

[0042] Accepting user-defined XML files and behavior tree code generation rule information from priori as input, then generating prompts for queries and tasks specifically for LLM behavior tree code generation, helping LLM understand the context of the query;

[0043] Prompt generation utilizes a series of static and dynamic techniques; static techniques use predefined, fixed structures and content in prompt templates to control and limit prompt formats; dynamic techniques select or generate prompt content in real time based on user input, context, and task changes to improve the accuracy and relevance of generated code. For example, prompt generation can dynamically select relevant entities and relationships based on user queries, then fill in the prompt template with context information;

[0044] First, define static components to create a reusable structured template;

[0045]

[0046] Then dynamically generate the final prompt based on user input, parse user input content including code language type, task, XML file, node description; build five variables required by the template: code language type, user's original task description or simplified task text, XML file obtained in step one, priori behavior tree code construction rules in step two, and behavior tree node function description input by the user in step one; fill the above variables into the predefined template to get the complete prompt.

[0047] The fourth step combines task-specific prompts with general code generation prompts to generate complete prompt information that guides the LLM to generate code that responds to user queries. The general code generation prompt information consists of the following parts:

[0048] The first general prompt information: configure system information; first, set the role as a code expert to guide the large model to generate complete functional code; second, the main task is determined to be code output, define quality standards, require accuracy and logical consistency; finally, the model must comply with subsequent guidelines; this method helps to control the large model's tendency to imagine to some extent, and ensures a relatively professional code generation style."

[0049] Second general prompt: Code writing rules; Explain to the large model the guidelines that must be followed in code generation; For example, remove redundant comments and text, standardize variable, function, and class naming, and add clear comments, etc.

[0050] Third general prompt: Specify file format; That is, specify file name, syntax language, and code block elements of individual code files, etc.

[0051] Fourth general prompt: Define multi-file structure; Illustrate the file structure through examples, and finally include a hierarchical tree structure at the end of the output; Used to clearly describe the location of each code file in the entire project;

[0052] Fifth general prompt: Strict requirements; Indicate that the large model strictly follow all specified conditions; Practical experience shows that including more specific terms will make the response more explicit; Thus improving efficiency and accuracy; Insisting on strict adherence to restrictions also applies to this aspect.

[0053] The complete prompt word guides the LLM to generate code as follows:

[0054] Based on the general rule prompt, define the general code generation guidance framework; Based on the task-specific prompt, extract the specific needs of the user query; Combine the general rule prompt and the task-specific prompt to form a structured complete prompt, optimize the prompt to reduce ambiguity, add context and step-by-step guidance; According to the prompt word, guide the LLM to generate professional C++ code as a code expert, and perform step-by-step decomposition behavior tree, register nodes, implement tickRoot execution logic, and configure log recorders to implement custom node logic. Guide the LLM to specify XML parsing errors, node registration integrity checks according to the prompt.

[0055] Step five, among different models, they show significant differences in the accuracy, functionality, and other key dimensions of code generation. Therefore, models that perform well in benchmark tests such as HumanEval should be prioritized, and these models not only should have successful cases in practical applications, but also should generate code with high interpretability. Such a choice helps to ensure the high quality, diversity of model training data, and close association with behavior tree logic. For the selected model, supervised fine-tuning should be performed to improve the performance of generating behavior tree code. For this purpose, a special dataset needs to be collected or constructed for supervised fine-tuning; The dataset should contain natural language descriptions of behavior trees (as input) and corresponding accurate code implementations (as output), and cover various types of behavior tree logic from common to complex, to ensure that the model can fully master the generation ability of behavior tree code.

[0056] The step six is to ensure that the large language model accurately generates code according to the prompt, and the following operation process is performed: the general prompt and the task-specific prompt are integrated in a structured format to build a complete prompt; a large language model supporting high-quality code generation is selected, and the complete prompt is input; the model outputs code meeting the structure, syntax and function requirements according to the prompt content, when multiple files are involved, the output includes complete code and corresponding file hierarchy, the code will run in a safe code execution environment, and the code and its running results generated during execution will be used as feedback to guide the model to debug itself, and the output performance of the model will be significantly improved by identifying and correcting errors in the code.

[0057] In the step seven, the running results in the code environment of the step six are obtained, and feedback is performed according to the running results.

[0058] If the running fails, detailed error information logs are captured, including error type, error location and error description, error logs are analyzed, and specific code statements and context where the error occurs are extracted.

[0059] If the running results do not meet the expected output, logical errors are identified by comparing the task requirements in the task-specific prompt; new correction prompts are formed by combining error information with original prompts; the corrected code segments are generated by inputting the corrected prompts into the model; or the user can directly modify the code content according to experience;

[0060] If the running results are successful but the user wants to adjust the code style (such as variable naming and code structure), the user is allowed to provide custom modification instructions.

[0061] The behavior tree code automatic generation system based on the large language model includes a user layer, a prompt engineering layer, a large model layer and a code execution layer, wherein the natural language description of the behavior tree is input, the corresponding accurate code implementation is output, and various common and even complex behavior tree logics are provided;

[0062] The user layer provides various information about the behavior tree, including behavior tree structure, behavior tree node detailed description, behavior tree code generation rule and specific user request, and transmits the related demand prompt to the prompt engineering layer;

[0063] The prompt engineering layer is composed of the generation of behavior tree code related demand prompt and general program comprehensive prompt, and the prompt engineering layer transmits the complete prompt to the large model for behavior tree related parameter data fine-tuning;

[0064] The large model layer generates corresponding code according to the prompt after receiving the prompt;

[0065] Code execution layer, compiled and executed in code executor; if encountering compilation error or running error, record error prompt in log, and input error prompt to large model as error prompt again, large model generates modified code according to supplemented error information and re-runs, so as to repeat; until code runs successfully or same error prompt repeats 5 times, then stop cycle, return last code and show to user, user can modify and check generated code.

[0066] The beneficial effects of the present application are:

[0067] The present application effectively solves the complexity and inconsistency problems in behavior tree code generation through structured prompt design and fine-tuning methods and steps. Combined with running verification and iterative correction, the present application realizes significant improvement of code quality and reliability, so as to meet the high requirements of task planning in complex scenarios. Through the complete process from XML parsing to code generation, verification and modification, the present application solves the problems of low efficiency, high error rate and insufficient interactivity of traditional manual coding, and realizes the efficiency and customizability of behavior tree code automatic generation. BRIEF DESCRIPTION OF DRAWINGS

[0068] Figure 1 is a schematic diagram of a behavior tree of a tree structure in the technical background.

[0069] Figure 2 is a schematic diagram of the framework principle of the behavior tree code automatic generation method based on a large language model provided by the embodiment of the present application.

[0070] Figure 3 is a flowchart of the behavior tree code automatic generation method based on a large language model provided by the embodiment of the present application.

[0071] Figure 4 is a schematic diagram of an example behavior tree of the behavior tree code automatic generation method based on a large language model provided by the embodiment of the present application.

[0072] Figure 5 is a schematic diagram of an XML file of an example behavior tree of the behavior tree code automatic generation method based on a large language model provided by the embodiment of the present application.

[0073] Figure 6 is a prompt schematic diagram based on behavior tree code generation of the behavior tree code automatic generation method based on a large language model provided by the embodiment of the present application.

[0074] Figure 7 is a schematic diagram of a general code generation prompt of the behavior tree code automatic generation method based on a large language model provided by the embodiment of the present application.

[0075] Figure 8This is a schematic diagram illustrating the automatic generation of C++ files containing the execution content by the behavior tree code automatic generation method based on a large language model provided in this embodiment of the invention. Detailed Implementation

[0076] The present invention will now be described in further detail with reference to the accompanying drawings.

[0077] This invention provides a method for automatically generating behavior tree code based on a large language model. The invention will be described in detail below with reference to the accompanying drawings.

[0078] The automatic code generation method based on behavior tree of a large language model provided by this invention can also be implemented by those skilled in the art using other steps. Figure 2 The framework principle of the behavior tree code automatic generation method based on a large language model provided by this invention is only a specific embodiment.

[0079] like Figure 2 As shown, the system for automatic code generation based on behavior tree of a large language model provided by this invention includes the following:

[0080] The system consists of a user layer, a prompting engineering layer, a large model layer, and a code execution layer. The selected model is then fine-tuned using a behavior tree. The natural language description of the behavior tree is taken as input, the corresponding precise code implementation is taken as output, and various common and even complex behavior tree logics are also included.

[0081] The user layer provides various information about the behavior tree, such as the behavior tree structure, detailed descriptions of behavior tree nodes, behavior tree code generation rules, and specific user requests, and transmits these as relevant requirement prompts to the prompting engineering layer.

[0082] The prompting engineering layer consists of requirement prompts related to generating behavior tree code and comprehensive prompts for general programs. This layer then transmits the complete prompts to the larger model for fine-tuning behavior tree-related parameter data.

[0083] In the large model layer, after receiving the prompt, the corresponding code is generated based on the prompt.

[0084] In the code execution layer, the code is compiled and executed within the code executor. If a compilation or runtime error is encountered, the error message is logged and re-entered as an error message to the main model. The main model then regenerates the modified code based on the supplementary error information and re-runs it, repeating this process. The loop stops when the code runs successfully or the same error message is repeated 5 times, at which point the final code is returned and displayed to the user, who can then modify and review the generated code.

[0085] like Figure 3 As shown, the automatic code generation method based on a large language model provided by this invention includes the following steps:

[0086] S101: Obtain a behavior tree model in an XML file format defined by a user and prompt information input by the user;

[0087] S102: Parse the obtained XML file and provide a generation rule of the behavior tree code;

[0088] S103: Combine the parsed XML file and the prompt information input by the user with the generation rule of the behavior tree code to generate a task-specific prompt, and ensure that the LLM understands the context of the query;

[0089] S104: Combine the task-specific prompt with a general code generation prompt to generate a complete prompt to guide the LLM to generate code responding to the user query;

[0090] S105: Select a suitable LLM, input the complete prompt information, and the LLM generates code according to the prompt;

[0091] S106: Run the generated code in a secure environment to ensure the safety of the code and the correctness of the output format;

[0092] S107: Display the execution result on a visual interface, and the user can review the result and modify the generated code.

[0093] As shown in the Figure 4 application, the behavior tree code automatic generation method based on a large language model covers several key sub-tree parts when applied to an example behavior tree construction, specifically including a target detection sub-tree, an executor selection sub-tree, and a target information feedback sub-tree.

[0094] The target detection sub-tree involves nodes such as "analyze target information" and "broadcast target information". The target detection sub-tree first determines whether the target is detected. If the target is not detected, the task may end; if the target information has been broadcast, further operations such as receiving feedback messages are involved to ensure effective detection and confirmation of the target.

[0095] The executor selection sub-tree involves nodes such as "there is an effective executor" and "select the optimal executor". The most suitable executor is selected from multiple executors to execute the task.

[0096] The target information feedback sub-tree involves nodes such as "receive executor execution result information" and "execute result feedback". After the executor is determined, the executor operates on the target, and the execution result obtained is implemented through node operation to realize the feedback of the execution result.

[0097] Users drag and drop nodes through the graphical interface Groot tool and connect these nodes according to logical needs to build the complete behavior tree model mentioned above.

[0098] like Figure 5 As shown, this is a schematic diagram of the XML file for the example behavior tree proposed in this invention. After the behavior tree model is constructed, it is saved as an XML file in Groot, specifically including the following content:

[0099] The behavior tree definition contains multiple "FallBack" selector nodes and "Sequence" sequential execution nodes. These nodes construct the logic of the behavior tree through different conditions and actions.

[0100] The tree node model lists multiple action IDs and condition IDs. Actions include broadcasting target information, collecting bidding information, sending XML, storing, and waiting for survey information. Conditions include whether the broadcast was successful, whether the collection was completed, and whether the current executor is valid. In summary, this behavior tree can be used to handle target-related tasks, information collection and processing, and task execution and feedback operations.

[0101] like Figure 6 As shown, the automatic code generation method based on behavior tree based on a large language model proposed in this invention includes the following:

[0102] The user request section includes the original prompts provided by the user. It generally includes information such as the overall task objective, implementation method, dependent tools or libraries, and the code files to be generated; a natural language description of the functional requirements for the behavior tree nodes; examples provided where necessary to improve the accuracy of the generated content; and additional guidelines, such as setting boundaries or further explaining the above information.

[0103] Example: "Please combine behaviortree.cpp and generate thecorresponding executable C++code file(including master code,node definitioncode,node definition library and corresponding cmake compilation file)according to the following behavior tree model."

[0104] The behavior tree structure takes the XML file saved by Groot in the previous step as input, and uses it as the structural representation of the behavior tree.

[0105] Example: "The following is the xml structure file of the behavior tree [filename.xml]"

[0106] Node Description: The parsed results of the XML file are taken as input, and the node description dimension is added to represent the node. The node is represented by four dimensions: Node ID, Node Type, Node Location, and Node Description. Example: {"NodeID":"x","node type":"x","node location":"x,y","node description":"x"}.

[0107] Node ID: The identifier of the node, representing the name of the node.

[0108] Node Type: The behavior tree is a tree structure used to control the behavior of artificial intelligence, which contains multiple node types. Among them, the combination node is used to control the execution order and logical relationship of the child nodes, such as the sequential node which executes the operations of the child nodes in order; the selection node selects one branch that can successfully execute from multiple child nodes. The decoration node is mainly used to modify the behavior attributes of the child nodes, such as the repetition node which allows the behavior of the child node to be executed a certain number of times or until a certain condition is met. The leaf node is the bottom layer of the behavior tree, representing the actual executable task.

[0109] Node Location: The behavior tree has a tree structure feature, and its overall structure is reflected by the record of the affiliation of each node.

[0110] Node Location: <x, y>

[0111] Among them, the first number x represents the node ID, meaning that this node belongs to the node with the corresponding number; the second number y indicates the order of the node in the child node set of the parent node, and this setting is based on the sequential nature of the behavior tree execution process.

[0112] Example: "Through this file,we can get that the behavior tree has[xx]sequential nodes,[xx]fallback nodes,[xx]action nodes,and[xx]conditionalnodes.The characterization results of each node are as follows:xxxxxx.

[0113] According to the description of each node above.Please generate thespecific behavior tree node actual node function instead of printing thestatement to represent the execution"

[0114] Behavior tree code rules, behavior tree execution code includes behavior tree execution main code, custom node code, custom node library.

[0115] Execution main code, responsible for loading behavior tree configuration, initializing behavior tree factory, registering nodes, executing behavior tree, and handling logs and state tracking. Summarize its writing rules as follows: ① Load the definition of behavior tree from XML file or other configuration source; ② Create an instance of BehaviorTreeFactory to generate and manage behavior tree nodes; ③ Register all custom nodes using the BT_REGISTER_NODES macro; ④ Call the tickRoot method to execute the behavior tree; ⑤ Configure and use loggers (such as StdCoutLogger, FileLogger, etc.) to track the state changes of the behavior tree.

[0116] Custom node code, defines specific behaviors and conditional judgments in the behavior tree, summarizes its writing rules as follows: ① Define the interface for each custom node, usually a function that returns NodeStatus ② Implement specific logic according to the function of the node, including conditional judgment and behavior execution ③ Register custom nodes to the behavior tree factory in the RegisterNodes function; ④ Handle input and output: define and use ports to receive input and provide output, interact with the blackboard to share data.

[0117] Custom node library, code responsible for defining namespaces, declaring related functions, facilitating subsequent code writing and mutual calling.

[0118] As Figure 7 shown, the general code generation prompt of the proposed behavior tree code automatic generation method based on large language model, combining task-specific prompts with a general code generation prompt, can generate complete prompt information guiding LLM to generate code responding to user queries.

[0119] First general prompt information: configure system information. First, set the role to a code expert to guide the large model to generate complete functional code. Second, the main task is determined as code output, defining quality standards, requiring accuracy and logical consistency. Finally, the model must comply with subsequent guidelines. This approach helps to control the imagination tendency of the large model to some extent and ensures a relatively professional code generation style.

[0120] Example: "Please change your role to a code expert. Your task is to generate the complete functional code based on the user's input. Your code should be unique and self-explanatory. You can generate code according to the guidelines mentioned below."

[0121] Second general prompt information: rules for code writing. Explain to the large model the guidelines that must be followed in code generation. For example, remove redundant comments and text, standardize variable, function, and class names, and add clear comments.

[0122] Example: "Each generated code should follow the following guidelines: 1. Returns the complete and correct code without additional explanation or text. 2. Avoid using abbreviations. The names of variables, functions, or classes should be self-evident, indicating their purpose and usage. 3. Contains clear guidance comments for the generated code."

[0123] Third general prompt: Specify file format. That is, specify the file name, syntax language, and code block of a single code file, and other elements.

[0124] Example: "Guide to multiple file generation: 1. Each code block corresponds to a code file that contains the file name and syntax language. 2. If the user does not provide it, the appropriate name is generated for each code file."

[0125] Fourth general prompt: Define the multi-file structure. Explain the file structure through examples, and finally include a hierarchical tree structure at the end of the output. Used to clearly describe the location of each code file in the entire project. The present invention generates five code files for a behavior tree based on a large language model, where the main function code main.cpp and its compilation file cmakelist.txt are located under the. / BehaviorTree / examples / folder, and the node code nodes.cpp, library file nodes.h, and its compilation file cmakelist.txt are located under the. / BehaviorTree / sample_nodes / folder.

[0126]

[0127] Fifth general prompt: Strictly follow the above rules. Indicate that the large model strictly follows all the specified conditions. Practical experience shows that including more specific terms will make the response more explicit, thereby improving efficiency and accuracy. Insisting on strict adherence to restrictions also applies to this aspect.

[0128] Example: "Please strictly follow all guidelines to ensure optimal performance."

[0129] As shown in Figure 8 , the behavior tree code automatic generation method based on a large language model proposed by the present invention generates a C++ file that implements the execution content.

[0130] The above merely illustrates the specific embodiments of the present application, but the protection scope of the present application is not limited thereto, and any modification, equivalent replacement and improvement within the technical range disclosed by the present application and within the spirit and principle of the present application should be covered within the protection scope of the present application.

Claims

1. A large language model-based behavior tree code automatic generation method, characterized in that, The method comprises the following steps: Step 1: Obtain the behavior tree model in XML file format defined by the user and the prompt information input by the user; Step 2: Parse the obtained XML file and provide the generation rule of the behavior tree code; Step 3: Combine the parsed XML file and the prompt information input by the user with the generation rule of the behavior tree code to generate task-specific prompts, ensuring that the LLM understands the context of the query; Step 4: Combine the task-specific prompts with the general code generation prompts to generate a complete prompt to guide the LLM to generate code to respond to the user's query; Step 5: Select a suitable LLM and input the complete prompt information, and the LLM generates code according to the prompt; Step 6: Run the generated code in a secure environment to ensure the security of the code and the correctness of the output format; Step 7: Display the execution results on the visualization interface, and the user audits the results and modifies the generated code.

2. The behavior tree code automatic generation method based on a large language model according to claim 1, characterized in that, In step 1, the user drags each node through the graphical interface Groot tool and connects each node according to the logic to build a complete behavior tree model; after the construction is completed, the system saves the behavior tree model as an XML file for further processing and code generation; The prompt information input by the user includes three parts: user request, behavior tree structure, and node description; The user request part describes the action that the user hopes the model to perform; The behavior tree structure part inputs the XML file constructed by the user; The node description part lists the various nodes in the behavior tree and their characteristics, including the relevant information of sequential nodes, fallback nodes, action nodes, and condition nodes.

3. The method of claim 2, wherein the method further comprises: In step 2, the XML file of the behavior tree structure part input is parsed, and the node number, node type, node description, and node relationship are extracted in combination with the node description part; according to the parsing result, each node is characterized by four dimensions, namely node ID, node type, node position, and node description; the prompt is generated according to the node description to generate the behavior tree execution code.

4. The behavior tree code automatic generation method based on a large language model according to claim 3, characterized in that, The behavior tree execution code includes the behavior tree main code, custom node code, and custom node library; The behavior tree main code is responsible for loading the behavior tree configuration, initializing the behavior tree factory, registering the nodes, executing the behavior tree, and processing the log and state tracking, and the writing rule is: ① Load the definition of the behavior tree from the XML file or other configuration source; ② Create an instance of BehaviorTreeFactory to generate and manage behavior tree nodes; ③ Register all custom nodes using the BT_REGISTER_NODES macro; ④ Call the tickRoot method to execute the behavior tree; ⑤ Configure and use the logger to track the state changes of the behavior tree; The custom node code defines the specific behavior and condition judgment in the behavior tree, and the writing rule is: ① Define the interface for each custom node, usually a function that returns a NodeStatus; ② Implement the specific logic according to the node's function, including conditional judgments and behavior execution; ③ Register the custom node in the behavior tree factory in the RegisterNodes function; ④ Handle input and output: define and use ports to receive input and provide output, interact with the blackboard to share data; The custom node library code is responsible for defining the namespace, declaring related functions, and facilitating subsequent code writing and mutual calling.

5. The method of claim 4, wherein the method further comprises: The interaction with the LLM in step three involves providing it with "prompts", which are natural language instructions that the user inputs as part of the task-specific prompts to provide context and guide the LLM in generating a text response; Accepting user-defined XML files and behavior tree code generation rule information from priori as input, then generating prompts and tasks that are specifically tailored to the behavior tree code generation LLM, helping the LLM understand the context of the query; Prompt generation utilizes a series of static and dynamic techniques; Static techniques use predefined, fixed structures and content in prompt templates to control and limit prompt format; dynamic techniques select or generate prompt content in real time based on user input, context, and task changes to improve the accuracy and relevance of generated code; Prompt generation dynamically selects relevant entities and relationships based on user queries, then fills in the prompt template with context information; First, define static components to create a reusable structured template; Then dynamically generate the final prompt based on user input, parse user input content including code language type, task, XML file, node description; build the five variables required by the template: code language type, user original task description or simplified task text, XML file obtained in step one, behavior tree code construction rules from priori in step two, and behavior tree node function description input by the user in step one; fill in the predefined template with the above variables to get the complete prompt.

6. The behavior tree code automatic generation method based on a large language model according to claim 5, characterized in that, In step four, combine the task-specific prompt with the general code generation prompt to generate complete prompt information that guides the LLM to generate code that responds to the user's query. The general code generation prompt information consists of the following parts in order: First general prompt information: configure system information; first, set the role as code expert to guide the large model to generate complete functional code; second, the main task is determined to be code output, define quality standards, require accuracy and logical consistency; finally, the model must comply with the following criteria; Second general prompt information: code writing rules; explain to the large model the criteria that must be followed in code generation; Third general prompt information: specify file format; specify file name, syntax language, and code blocks of individual code files, etc.; Fourth general prompt information: define multi-file structure; illustrate the file structure through examples, and finally include a hierarchical tree structure at the end of the output; used to clearly describe the location of each code file in the entire project; The fifth general prompt information: strict requirements; instruct the large model to strictly follow all specified conditions; practical experience shows that including more specific terms will make the response more explicit; The complete prompt word guides the LLM to generate code as follows: Based on the general rule prompt, define the general code generation guidance framework; based on the task-specific prompt, extract the specific requirements of the user query; combine the general rule prompt and the task-specific prompt to form a structured complete prompt, optimize the prompt to reduce ambiguity, add context and step-by-step guidance; guide the LLM to generate professional C++ code as a code expert, and perform step-by-step decomposition of the behavior tree, register nodes, implement tickRoot execution logic, and configure log recorders to implement custom node logic; guide the LLM to specify XML parsing errors, node registration integrity checks according to the prompt.

7. The method of claim 6, wherein the method further comprises: Step five, for the selected model, perform supervised fine-tuning to improve the performance of generating behavior tree code; collect or build a specialized dataset for supervised fine-tuning; the dataset should contain natural language descriptions of behavior trees and corresponding accurate code implementations, and cover various behavior tree logics from common to complex, to ensure that the model can fully master the generation of behavior tree code.

8. The behavior tree code automatic generation method based on a large language model according to claim 7, characterized in that, Step six, integrate the general prompt and task-specific prompt in a structured format to build a complete prompt; Select a large language model that supports high-quality code generation and use the complete prompt as input; The model outputs code that meets the structure, syntax, and functional requirements based on the prompt content. When multiple files are involved, the output includes complete code and corresponding file hierarchy, and the code will run in a secure code execution environment. The code and its running results will be used as feedback to guide the model to debug itself, and the model's output performance will be significantly improved by identifying and correcting errors in the code.

9. The method of claim 8, wherein the method further comprises: In step seven, obtain the running results in the code environment of step six and provide feedback based on the running results; If the running fails, capture detailed error information logs, including error type, error location, and error description, analyze the error logs, and extract the specific code statements and context where the error occurred; If the running results do not meet the expected output, identify logical errors by comparing the task requirements in the task-specific prompt; Form a new corrected prompt by combining the error information with the original prompt; Input the corrected prompt into the model to generate the repaired code segment; Or support users to directly modify the code content based on experience; If the running results are successful but the user wants to adjust the code style, allow the user to provide custom modification instructions.

10. A behavior tree code automatic generation system based on a large language model, characterized by, It includes a user layer, a prompt engineering layer, a large model layer, and a code execution layer. The natural language description of the behavior tree is input, and the corresponding accurate code implementation is output. It covers various behavior tree logics from common to complex. The user layer provides various information about the behavior tree, including behavior tree structure, behavior tree node detailed description, behavior tree code generation rules, and specific user requests, and transmits related demand prompts to the prompt engineering layer. The prompt engineering layer is composed of prompt generation behavior tree code related requirement and general program, and the prompt engineering layer transmits the complete prompt to the large model for fine-tuning of behavior tree related parameter data; The large model layer receives the prompt and generates corresponding code according to the prompt; The code execution layer compiles and executes in the code executor; if a compilation error or a running error is encountered, the error prompt is recorded in the log and input to the large model as an error prompt, the large model generates modified code according to the supplemented error information and re-runs, and the process is repeated; until the code runs successfully or the same error prompt is repeated for 5 times, the cycle is stopped, the last code is returned and displayed to the user, and the generated code can be modified and checked by the user.

Citation Information

Patent Citations

  • Method and system for automatically generating behavior tree codes

    CN106959850A

  • Method and device for automatically generating vehicle behavior tree code

    CN117472342A

Cited By

  • System and method for designing mRNA (messenger ribonucleic acid) vaccine sequence based on intelligent agency of large language model

    CN121483390A

  • Mrna vaccine sequence design system and method based on large language model intelligent agent

    CN121483390B

  • Behavior tree automatic generation method and device based on large language model and electronic equipment

    CN122133823A