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

By combining node variable context objects with a lightweight large language model, the problems of unreliable behavior tree generation results and high deployment costs in existing technologies are solved, achieving efficient and stable automatic behavior tree generation and supporting continuous optimization of system capabilities.

CN122133823APending Publication Date: 2026-06-02INFORMATION SCI RES INST OF CETC
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
INFORMATION SCI RES INST OF CETC
Filing Date
2026-05-07
Publication Date
2026-06-02

AI Technical Summary

Technical Problem

Existing methods for automatically generating behavior trees based on large language models suffer from problems such as high deployment costs, unreliable generation results, lack of expert experience integration, poor usability of generated content, and uncontrollable generation results, leading to low efficiency in practical engineering applications.

Method used

By constructing a node variable context object, injecting behavior tree syntax rules and resource constraints, and combining it with a lightweight large language model for generation, and iteratively optimizing it through evaluation operator checks and feedback mechanisms, the generated results are finally stored in an expert case library, forming a closed-loop learning process.

Benefits of technology

It significantly improves the availability and stability of behavior tree generation, reduces deployment costs, enhances adaptability to complex tasks, and supports continuous iterative expansion of system capabilities.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122133823A_ABST
    Figure CN122133823A_ABST
Patent Text Reader

Abstract

This application discloses a method, apparatus, and electronic device for automatically generating behavior trees based on a large language model, relating to the fields of artificial intelligence and automation control technology. The method includes: acquiring task description information, constructing node variable context objects, injecting structured prompts, and forming a resource-constraint-aware generation context; retrieving high-quality cases that meet a quality threshold based on the semantic vector of the task description, filtering dynamically few-sample examples using a selection algorithm and embedding generation prompts; calling a locally deployed large language model to generate a behavior tree, performing grammar checks and logic defect detection on the generated results through evaluation operators, converting failed detection results into structured feedback information, and driving the model to perform minimization iterative refinement until the checks are passed or the maximum number of iterations is reached. This solves the problems of low usability, poor stability, and high deployment cost of behavior tree generation using large language models, enabling a lightweight large language model to achieve approximately 90% generation success rate on consumer-grade hardware.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the fields of artificial intelligence and automated control technology, and in particular to a method, apparatus and electronic device for automatic generation of behavior trees based on a large language model. Background Technology

[0002] Behavior trees are hierarchical behavioral logic structures that define rules for the complex behavior of intelligent agents. They have wide applications in physical and simulation domains, such as robot control and autonomous decision-making for game agents. By decomposing complex tasks into manageable sub-task units, behavior trees provide stronger modularity than finite state machines through a tree-like organization. The core node types of behavior trees include control flow nodes (selectors, sequencers, parallelizers, decorators) and execution nodes (action nodes, condition nodes). Each node returns one of three states after execution: success, failure, or running, propagating upwards along the tree structure to guide the overall execution flow. In robotic systems, behavior trees occupy an intermediate layer connecting the task planning module and the control execution module, supporting non-blocking execution and enabling rapid response to environmental changes.

[0003] A complete behavior tree control system encompasses not only the behavior tree itself but also supporting mechanisms such as visual editing, parsing and execution scheduling, action interface encapsulation, perception condition judgment, and blackboard variable management. When designing behavior trees, engineers need to repeatedly switch between high-level task semantics and low-level control details, understanding both task planning requirements and environmental variables and actuator constraints. As the size of the behavior tree increases, the number of nodes and behavior branches grows exponentially, significantly increasing the cognitive burden of manually maintaining global consistency, avoiding logical conflicts, and ensuring abnormal path coverage. Traditionally, behavior tree writing has heavily relied on specialized engineers, becoming a key bottleneck restricting the efficiency of deploying complex intelligent agent systems.

[0004] To address the inefficiency of manual behavior tree generation, researchers have proposed several methods for automatic behavior tree generation. Methods based on expert case reuse employ a paradigm of case library accumulation, similar case retrieval, and case reuse adaptation, but they struggle to cover unseen scenarios and heavily rely on manual annotation. Evolutionary computation-based methods transform behavior tree generation into a global optimization search problem, automatically discovering the behavior tree structure through iterative population evolution; however, they suffer from low search efficiency, high computational costs, and difficulty in controlling the generated structure. All of these methods exhibit significant limitations in terms of controllability, flexibility, and generality.

[0005] In recent years, behavior tree generation methods based on large language models have adopted a simple input-output dialogue paradigm to convert natural language instructions into behavior tree text. However, existing methods suffer from the following technical problems: First, they rely on large commercial models with hundreds of billions of parameters, resulting in high deployment costs; second, it is difficult for large language models to accurately understand the grammatical constraints and available node resources of behavior trees, leading to the generation illusion problem; third, they lack evaluation and verification mechanisms for the generated results, resulting in poor system stability; fourth, they lack expert experience fusion mechanisms, hindering continuous iterative expansion of system capabilities; and fifth, they cannot precisely control the grammar of the generated behavior trees, resulting in poor usability of the generated content. These problems severely restrict the application of automatic behavior tree generation methods based on large language models in practical engineering.

[0006] Therefore, there is an urgent need for a technical solution for automatic generation of behavior trees that can solve the above problems. Summary of the Invention

[0007] The present invention aims to provide a method, apparatus and electronic device for automatic generation of behavior trees based on a large language model, so as to overcome the shortcomings of the prior art. The technical problem to be solved by the present invention is achieved through the following technical solutions.

[0008] According to a first aspect of this application, a method for automatically generating behavior trees based on a large language model is provided, comprising: Obtain a behavior tree generation request, the generation request including task description information, agent type information, and available node configuration information; Construct a node variable context object, which contains the identifier, type, attributes, and port definitions of available nodes, as well as a variable constraint dictionary; Based on the node variable context object and the task description information, system prompt words and task prompt words are constructed. The system prompt words include behavior tree syntax specifications, node writing rules and output format constraints. The task prompt words include agent information, task description and registration node information, realizing resource constraint injection. The task description information is converted into a semantic vector. Cosine similarity is calculated based on the semantic vector and the pre-calculated semantic vector in the expert case library. The few sample examples are dynamically filtered by the Top-K selection algorithm with quality score filtering and diversity constraints. The few sample examples are embedded into the system prompt words to obtain the complete generated prompt words. The large language model is invoked to generate a behavior tree based on the complete generated prompt words, and the evaluation operator is checked on the behavior tree; If the evaluation operator check fails, the check result is converted into structured feedback information, which includes error type, error location, error description and correction suggestions. Based on the structured feedback information, refined prompt words are constructed, and the large language model is called to perform minimum iterative correction on the behavior tree until the evaluation operator check passes or the maximum number of iterations is reached. Output the behavior tree that passes the evaluation, and store the generated results in the expert case library.

[0009] Preferably, the construction node variable context object includes: Load default node configuration information; Extract user-defined node information from the generated request; Based on the user-defined node priority merging strategy, the default node configuration is merged with the user-defined node; Encapsulate the variable dictionary into the merged node variable context object.

[0010] Preferably, the Top-K selection algorithm for the diversity constraint includes: Initialize the selected case set; Candidate cases that have passed quality filtering are traversed from high to low based on cosine similarity. Calculate the semantic similarity between the current candidate case and each case in the selected case set; If the similarity between the current candidate case and any selected case is greater than or equal to the diversity threshold, then the current candidate case is skipped; otherwise, the current candidate case is added to the set of selected cases. Repeat the above traversal steps until the number of selected cases reaches the target number K or the candidate cases have been traversed.

[0011] Preferably, the quality score threshold for quality filtering is 0.6, the diversity threshold is 0.85, and the target quantity K ranges from 3 to 5.

[0012] Preferably, the evaluation operator check includes syntax checking and logic defect detection; The syntax checks include: root node verification, node structure validity check, node registration verification, node attribute verification, and variable reference validity check; The logic defect detection includes: checking the number of child nodes of the control node according to rules, and checking for meaningless nesting.

[0013] Preferably, the refined prompt words include refined system prompt words, the original behavior tree, and the structured feedback information; the refined system prompt words define the large language model as a behavior tree correction expert, requiring minimal modification to the original behavior tree, correcting only the problematic parts while retaining other correct content unchanged.

[0014] Preferably, the large language model is a locally deployed lightweight language model that performs efficient inference through an inference engine framework; the generated parameters include: temperature parameter T is 0.6, Top-p sampling parameter p is 0.95, and the maximum number of output tokens N is 8192.

[0015] According to a second aspect of this application, an automatic behavior tree generation apparatus based on a large language model is provided, employing the above-described automatic behavior tree generation method based on a large language model, comprising: The context building module is used to obtain the behavior tree generation request, build a node variable context object containing available node definitions, variable constraint dictionary and agent type information, and build system prompt words and task prompt words based on the node variable context object to realize the structured injection of behavior tree syntax specifications and node resource constraints; The dynamic sample retrieval module is used to convert task description information into semantic vectors, perform cosine similarity calculation based on the semantic vectors and pre-calculated vectors in the expert case library, dynamically filter few sample examples through a Top-K selection algorithm with quality score filtering and diversity constraints, and embed the few sample examples into system prompt words to form complete generated prompt words; The behavior tree generation module is used to call the large language model to generate a behavior tree based on the complete generated prompt words; The evaluation and refinement module is used to perform evaluation operator checks on the generated behavior tree, convert the results of the checks that fail into structured feedback information containing error type, error location, error description and correction suggestions, and construct refinement prompt words based on the structured feedback information to drive the large language model to perform minimization iterative correction; The case accumulation module is used to store the generated results into the expert case library and update the semantic vectors, quality scores and usage statistics of the cases.

[0016] According to a third aspect of this application, an electronic device is provided, comprising: a memory and a processor; the memory stores a computer program, and the processor executes the computer program to implement the above-described automatic behavior tree generation method based on a large language model.

[0017] According to a fourth aspect of this application, a computer-readable storage medium is provided having a computer program stored thereon, which, when executed by a processor, implements the above-described automatic behavior tree generation method based on a large language model.

[0018] The embodiments of the present invention have the following advantages: (1) Significantly improve the usability and stability of generation: By using a closed-loop refining and optimization mechanism based on the feedback of the evaluation operator, the generated behavior tree is subjected to syntax checking and logical defect detection. Error information is transformed into structured feedback to drive model iteration and correction, thereby increasing the success rate of generating lightweight large language models to over 90%, effectively solving the technical problem of poor usability of existing generation results.

[0019] (2) Effectively reduce deployment costs and response latency: This application is designed for lightweight large language models and supports local deployment of consumer-grade graphics processing units. It does not rely on large-scale commercial models or high-performance computing servers. While ensuring the quality of generation, it significantly reduces hardware costs and inference latency, and is suitable for practical application environments with limited computing resources.

[0020] (3) Accurate integration of expert experience: By using a few-sample prompt learning mechanism based on dynamic retrieval, semantic vector similarity retrieval combined with quality score filtering and diversity constraints, the most relevant high-quality expert cases are automatically selected as examples, enabling the large language model to learn and reuse expert writing patterns, improving the quality of generation while enhancing the system's adaptability to complex tasks and new scenarios.

[0021] (4) Enhance grammatical constraint awareness and resource controllability: Through the resource constraint injection mechanism based on structured context assembly, the behavior tree grammatical specifications, complete information of available nodes and variable constraints are uniformly injected into the prompt words, so that the large language model can accurately understand the generation boundary, avoid using unregistered nodes or violating grammatical rules, and significantly improve the legality and controllability of the generated behavior tree.

[0022] (5) Support for continuous iteration and expansion of system capabilities: During the online service process, the generated results are automatically deposited into the expert case library. Combined with pre-calculated semantic vectors, quality scores and dynamic usage statistics feedback, the task scenarios covered by the case library are continuously enriched, and the system's generation capabilities are continuously optimized and evolved with the accumulation of cases. Attached Figure Description

[0023] Figure 1 This is a flowchart of a behavior tree automatic generation method based on a large language model according to this application; Figure 2 This is a structural block diagram of an automatic behavior tree generation device based on a large language model according to this application; Figure 3 This is a structural block diagram of an electronic device according to this application; Figure 4 This is a structural block diagram of a computer-readable storage medium according to this application. Detailed Implementation

[0024] It should be noted that, unless otherwise specified, the embodiments and features described in this application can be combined with each other. The present invention will now be described in detail with reference to the accompanying drawings and embodiments.

[0025] It should be noted that the above detailed descriptions are exemplary and intended to provide further explanation of this application. Unless otherwise specified, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this application pertains.

[0026] Example 1: like Figure 1 As shown in the embodiments of this application, an automatic behavior tree generation method based on a large language model is provided. Through three core mechanisms, namely structured context assembly, dynamic retrieval of few-sample prompts for learning, and evaluation operator feedback refinement, the method solves the problems of low behavior tree writing efficiency, poor controllability of automatic generation methods, and instability of large language model applications in the prior art.

[0027] The method includes the following steps: Step 1: Obtain the behavior tree generation request, which includes task description information, agent type information, and available node configuration information; The task description information (e.g., instructional text in natural language, such as instructing a drone to fly over a specified altitude and target area for 10 minutes and then return) represents the high-level behavioral objectives that the user expects the agent to complete. Agent type information (e.g., category identifiers such as robot, drone, game NPC, industrial controller, etc.) defines the perception capabilities, actuator interfaces, and environmental interaction constraints upon which the behavior tree operation depends. Available node configuration information (e.g., structured data in JSON format, including node ID, node type, input / output port definitions, attribute fields, and value range constraints) clarifies the set of atomic behavioral units registered and callable in the current system. In this embodiment, these three types of information together constitute the complete input boundary of the generated task, providing the original data foundation for the subsequent construction of structured context objects, ensuring that the behavior tree generation process is always constrained by real available resources and the characteristics of the operating platform.

[0028] This application can, for example, receive a JSON payload submitted by a front-end web interface via an HTTP POST request, and parse out the `task_description` field as task description information, the `agent_type` field as agent type information, and the `nodes_config` field as available node configuration information. Alternatively, it can read a local YAML configuration file using a command-line tool and extract the corresponding key-value pairs to load the information. Furthermore, it can call an SDK interface via a test script, passing in a pre-constructed object instance, which is then restored into structured request data by the internal serialization module. Based on any of the above methods, this application obtains a complete, accurate, and reproducible parsing result for the behavior tree generation request, providing consistent input for subsequent context modeling.

[0029] Step 2: Construct a node variable context object, which contains the identifier, type, attributes, and port definitions of available nodes, as well as a variable constraint dictionary; The available node identifier (e.g., a unique node ID in string form, such as node_001 or DetectColor) is used to uniquely identify node instances in the behavior tree structure; the available node type (e.g., Sequence or Selector in control flow nodes, or Action or Condition in execution nodes) is used to constrain the insertion position of the node in the tree and its child node organization rules; the available node attributes (e.g., parameters required for node operation, such as speed, timeout, color_threshold, etc., and their data types and default values) are used to define the specific configuration dimensions of the node's functionality; the available node port definition (e.g., the name, direction, data type, and connection constraints of input port_input_port and output port_output_port) is used to describe the data flow relationship between the node and other nodes or blackboard variables; the variable constraint dictionary (containing blackboard variable names, types, and initial values) is used to ensure the legality and security of variable references during behavior tree runtime. In this embodiment, all the above elements are encapsulated into a unified node variable context object (NodeVarContext), serving as an explicit modeling carrier for resource semantics, providing structured, interpretable, and verifiable metadata support for prompt word construction.

[0030] This application can, for example, extract the ID, type, properties, and ports fields of each node object from the available node configuration information, and map them to the corresponding properties of the NodeVarContext class. Alternatively, it can load variable constraint information from independent configuration files or database query results, validate it, and then merge it into the same context object. Furthermore, it can dynamically parse the schema definition of the node configuration using reflection, automatically generate field binding relationships, and populate the context object. Based on any of the above methods, this application obtains a node variable context object with complete node metadata and variable constraint semantics, ensuring that the granularity of subsequent prompt word injection is sufficient to support the LLM's accurate understanding and compliant generation of the behavior tree structure.

[0031] Step 3: Based on the node variable context object and the task description information, construct system prompt words and task prompt words. The system prompt words include behavior tree syntax specifications, node writing rules and output format constraints. The task prompt words include agent information, task description and registration node information, and realize resource constraint injection. The system prompts (e.g., role definitions and rule descriptions for large language models, the core content of which includes: the role is set as a behavior tree generation AI; the behavior tree syntax specification is defined using JSON Schema, which describes the standardized text representation structure of the behavior tree; the JSON Schema includes node type definitions, field constraint rules, and hierarchical organization relationships, wherein the "$ref" field enables recursive references to the node structure, allowing each node's child nodes to continue to expand according to the same structure, thereby forming a tree-like data structure that supports arbitrary levels of nesting; at the same time, the JSON Schema is also used to limit the uniqueness of the root node, the legality of node references, and the child node constraint rules of specific types of nodes, so as to achieve automatic verification and parsing of behavior tree data;) Node writing rules include semantic constraints such as attribute assignments must conform to predefined types and value ranges, and port connections must meet data type matching requirements. Output format constraints include the final output being structured text that strictly conforms to the JSON Schema definition. These rules are used to inject domain-wide, static, and strongly constrained syntactic knowledge into the model. Task prompts (e.g., contextualized text for the current generated task, whose core content includes agent type information (e.g., agent_type: quadruped_robot), task description information (e.g., task_description: "Make the quadruped robot cross the street and stop after recognizing the red obstacle ahead") are used to inject dynamic, task-specific, and weakly constrained user-defined context into the model. In this embodiment, the dual-prompt collaboration mechanism of system prompts and task prompts achieves explicit injection of both behavior tree syntactic norms and available resource constraints, enabling the large language model to both follow general structural rules and accurately adapt to the actual capability boundaries of the current platform during the generation process.

[0032] The resource constraint injection mechanism includes the following processing flow: Step 31: Create NodeVarContext (Node Variable Context). First, load the default node configuration information, which defines the standard control node types (including Sequence nodes, Selector nodes, Parallel nodes, Inverter nodes, etc.) and attribute constraints of each node pre-defined by the behavior tree engine. Then, extract user-defined node information from the generation request. The user-defined nodes include the identifiers, parameter types, input ports, and output port definitions of action nodes and condition nodes. Using a user-defined node-first merging strategy, merge the default node configuration with the user-defined nodes to form a complete list of available nodes. Finally, encapsulate the variable constraint dictionary (containing blackboard variable names, types, and initial values) into the node variable context object.

[0033] Step 32: Create a task generation context object, including: task description information, node variable context objects, and agent type information. This task generation context serves as a unified data carrier; downstream modules directly use the data in the context object without repeatedly loading configurations, ensuring data consistency and module decoupling.

[0034] Step 33: Create a generation configuration object, including: generation method selection (whether to enable dynamic sample hints), model parameter configuration (temperature parameters, sampling parameters, maximum output length), and execution parameter settings (maximum number of retries, timeout).

[0035] Step 34: Construct system prompts and task prompts. System prompts include: role definition (defining the large language model as a professional behavior tree generation AI), writing specifications (node ​​usage rules, parameter configuration rules, child node number constraints, etc.), and output format constraints (JSON Schema definition, specifying the complete structural format of the behavior tree). Task prompts include: agent type information, task description text, available variable dictionary, and registered node information (a complete list of ID, type, attribute definitions, and port definitions for each node). By fully injecting the behavior tree syntax specifications and available node resources into the prompts, the large language model can accurately understand the syntax constraints and strictly generate behavior trees within the scope of registered nodes, fundamentally avoiding the generation illusion problem caused by using undefined nodes.

[0036] Step 4: Convert the task description information into a semantic vector, perform cosine similarity calculation based on the semantic vector and the pre-calculated semantic vector in the expert case library, dynamically filter out few sample examples through the Top-K selection algorithm with quality score filtering and diversity constraints, and embed the few sample examples into the system prompt words to obtain the complete generated prompt words; The semantic vector (e.g., a 768-dimensional floating-point array generated by the lightweight text encoding model Sentence-BERT) is used to map unstructured task description information into points in a dense vector space, giving it measurable semantic distance. The expert case library (e.g., an SQLite database or memory-mapped file storing historically generated successful behavior tree cases, each case associated with its task description, generated behavior tree JSON, pre-computed semantic vector, quality score, and usage statistics) carries verified expert experience and knowledge. Quality score filtering (e.g., filtering cases based on a preset threshold of 0.6) is used to evaluate their quality. A Boolean filter is applied to the score field, retaining only candidate cases with a score ≥ 0.6 to ensure the basic reliability of the selected examples. A Top-K selection algorithm with diversity constraints (e.g., after sorting candidate cases in descending order of cosine similarity, each case is checked for similarity ≥ 0.85 with any case in the selected set; if so, it is skipped, otherwise it is added until K=3 cases are selected) is used to avoid example redundancy and improve generalization ability. Few-sample examples (e.g., paired structured samples containing input: task description + available nodes + variable constraints, output: corresponding behavior tree JSON) are used to provide the model with a mapping example from task to behavior tree. In this embodiment, this step, through a semantically driven dynamic retrieval mechanism, accurately injects expert experience into the generation process in the form of few samples, significantly improving the LLM's ability to understand and generate complex behavioral logic without increasing model parameters.

[0037] This application obtains K few sample examples with high relevance, high quality and high diversity based on any of the above methods, and embeds them into the end of the system prompt word in a standard format to form the complete generated prompt word (P = S_sys + E + Q) finally delivered to the large language model.

[0038] The few-shot prompting learning mechanism achieves dynamic selection and embedding of high-quality expert cases through three stages. The complete prompt word P input to the large language model consists of three parts: P = Ssys + E + Q, where Ssys is the system prompt word (defining task specifications and constraints), E is the dynamic few-shot example, and Q is the user task prompt word.

[0039] Phase 1: Similarity Calculation. The current task description information is converted into a fixed-dimensional semantic vector using a semantic encoding model. Cosine similarity is then calculated between this vector and the pre-computed semantic vectors of task descriptions stored in the expert case library. The formula for calculating cosine similarity is: sim(u,v)=(u·v) / (||u||·||v||), where u is the semantic vector of the current task description, and v is the semantic vector of each case task description in the case library.

[0040] Phase 2: Real-time Filtering and Top-K Selection with Diversity Constraints. Quality Filtering: Using pre-calculated quality scores from the expert case library, cases with quality scores below a threshold (recommended value of 0.6) are filtered, retaining only high-quality cases for subsequent selection. Similarity Ranking: Candidate cases that pass quality filtering are sorted in descending order of cosine similarity. Top-K Selection with Diversity Constraints: The selected case set S is initialized as an empty set; candidate cases are traversed from high to low similarity, calculating the semantic similarity between the current candidate case and each case in the selected case set S; if the similarity between the current candidate case and any selected case is greater than or equal to the diversity threshold (recommended value of 0.85), the candidate case is skipped; otherwise, the candidate case is added to the selected case set S; the above traversal process is repeated until the number of selected cases reaches the target number K (recommended value of 3 to 5) or all candidate cases have been traversed. This diversity constraint mechanism avoids selecting cases with highly similar content, prevents redundancy of few samples, ensures that selected cases cover different task modes and writing styles, and improves the pattern diversity learned by the large language model.

[0041] Phase 3: Sample Formatting and Complete Prompt Assembly. The selected K cases are formatted as few-sample instances E, each containing an input (task description, available nodes, variable constraints) and an output (corresponding behavior tree JSON structure). The system prompt, few-sample instances, and task prompt are concatenated into a complete generated prompt P according to the format P=Ssys+E+Q. Generation parameters are configured (temperature parameter T=0.6, Top-p sampling parameter p=0.95, maximum output token count N=8192). The locally deployed large language model is invoked for efficient inference through the inference engine framework. The returned JSON response is parsed and converted into a behavior tree data structure.

[0042] In some embodiments, the expert case library also supports an online accumulation mechanism: after online generation is completed, the generated data (task description, behavior tree, etc.) is automatically extracted and stored in the case library, and the task description is converted into a semantic vector for storage; the case is scored for quality using a large language model and the scoring results are stored; the number of times a case is selected and the success rate after use are recorded for dynamically adjusting case weights and continuously optimizing the matching strategy.

[0043] Step 5: The large language model is invoked to generate a behavior tree based on the complete generated prompt words, and the behavior tree is checked by the evaluation operator; this step realizes real-time quality gating of the generated results, providing a basis for judgment for subsequent closed-loop refinement.

[0044] This application can, for example, initiate a `generate()` request to the local LLM service via a vLLM client, passing in the complete generation prompt words and preset parameters, and receiving a JSON-formatted response. Alternatively, it can call a JSONSchema validator (such as the `jsonschema` Python library) to perform format validation on the response text. Furthermore, it can load a pre-compiled set of evaluation operator rules and perform recursive traversal and rule matching on the validated JSON structures. Based on any of the above methods, this application obtains a comprehensive, automated, and reproducible evaluation result for the generated behavior tree, ensuring that only legal and reasonable structures enter subsequent processes.

[0045] Evaluation operators are rule checkers predefined according to the behavior tree syntax specification and domain constraints. They include two types: syntax checkers, which are used to verify the syntactic correctness of the behavior tree structure, specifically including root node verification (the behavior tree must have one and only one root node), node structure legality check (the child node types of each node must conform to the specification), node registration verification (all used nodes must exist in the list of registered nodes), node attribute verification (the type and value range of each node attribute must conform to the definition), and variable reference legality check (the referenced blackboard variables must be defined in the variable dictionary); and logic defect detectors, which are used to detect logical defects in the behavior tree, specifically including rule checks on the number of child nodes of control nodes (Inverter nodes must have exactly one child node, and Sequence nodes and Parallel nodes must have at least two child nodes) and meaningless nesting checks (multiple meaningless nesting of Sequence nodes).

[0046] Step Six: If the evaluation operator check fails, the check result is converted into structured feedback information. The structured feedback information includes error type, error location, error description and correction suggestions. Based on the structured feedback information, a refined prompt word is constructed, and the large language model is called to perform a minimum iterative correction on the behavior tree until the evaluation operator check passes or the maximum number of iterations is reached. The structured feedback information (e.g., a JSON object containing fields such as error_type (e.g., SYNTAX_ERROR or LOGIC_DEFECT), error_location (e.g., a JSONPath expression for / root / children / 1 / type), error_description (e.g., node ID 'TurnRight' is not declared in the registered node list), and correction_suggestion (e.g., please replace this node with 'TurnLeft' or 'TurnAround' which exists in the registered list)) is used to transform abstract check failure results into corrective instructions that the model can understand and act upon. Refined prompts (e.g., a composite prompt containing three parts: a refined system prompt defining the model as a behavior tree correction expert, requiring it to only modify the erroneous parts and retain the remaining correct content; the original behavior tree JSON text; and the structured feedback information) are used to guide the model to perform corrections with minimal perturbation. The maximum number of iterations (e.g., an integer of 2, specified by system configuration parameters) is used to prevent infinite loops and ensure service response timeliness. In this embodiment, this step constructs a closed-loop optimization chain of generation-evaluation-feedback-correction, enabling the lightweight model to achieve accurate repair through structured guidance even after a single generation failure, significantly improving the stability and success rate of the final output.

[0047] This application could, for example, serialize the error object returned by the evaluation operator into a standard JSON structure as structured feedback information; it could also, for example, concatenate the original behavior tree JSON string, the refined system prompt word template, and the structured feedback information in a fixed order to form a new prompt word; further, it could also, submit the refined prompt word back to the same LLM service and reuse the same inference parameters for generation. Based on any of the above methods, this application obtains a minimized, targeted, and verifiable corrected version of the original behavior tree and continuously executes the evaluation-correction loop until it passes or reaches the upper limit.

[0048] For cases where the evaluation operator fails the check, the check results are converted into structured feedback information. This structured feedback information helps the large language model accurately locate the problem and make targeted corrections.

[0049] Refined prompt word construction. The refined system prompt word defines the correction expert role of the large language model, requiring the model to perform minimal modifications to the original behavior tree based on feedback information, correcting only the problematic parts while keeping other correct content unchanged; the refined system prompt word, the original behavior tree Ti, and the structured feedback information are combined into the refined prompt word.

[0050] Refined Generation. The large language model is invoked to generate a revised behavior tree Ti+1 based on the refined prompt words.

[0051] A second evaluation check is performed. The evaluation operator check from Phase 1 is re-executed for Ti+1 to determine whether it passes or requires further iteration. The iteration terminates when the evaluation operator check passes, or when the maximum number of iterations N is reached (recommended value is 2). Through this closed-loop refinement mechanism, the system can automatically detect and correct generation errors, significantly improving the usability and stability of the generated results.

[0052] Step 7: Output the behavior tree that passes the evaluation and store the generated results in the expert case library.

[0053] The evaluated behavior tree (e.g., JSON-formatted structured data that has passed all syntax and logic checks) serves as the final usable output and can be directly delivered to the downstream behavior tree parsing and execution module for loading and running. The expert case library (e.g., an instance of the same case library used above) is used to persistently store the complete cases successfully generated this time, including task description information, agent type information, available node configuration information, the generated behavior tree JSON, the semantic vector used in this generation, quality score (either secondary scoring by LLM or a default setting of 1.0), usage statistics (such as a first-time entry marker), and other metadata. In this embodiment, this step not only completes the delivery of a single task but also, through an automatic knowledge accumulation mechanism, enables the system's capabilities to continuously evolve with increasing usage frequency, forming a positive feedback loop of generation as learning.

[0054] This application could, for example, write the evaluated behavior tree JSON to a specified directory on the local file system and synchronously update the corresponding record in the SQLite database; it could also, for example, call a vectorization service to re-encode the task description and write the new vector along with the quality score into the Faiss index; further, this application could also store the generation time, number of iterations, number of correction nodes, and other operational metrics as additional metadata in the case library for subsequent quality analysis and strategy optimization. This application achieves reliable output of the generated results and sustainable knowledge accumulation based on any of the above methods, supporting the long-term evolution of the system.

[0055] This application constructs a node variable context object containing node identifiers, types, attributes, ports, and variable constraints by jointly parsing task description information, agent type information, and available node configuration information. Leveraging the dual-track collaboration of system prompts and task prompts, behavior tree syntax rules, node writing rules, output format constraints, and runtime resource context are synchronously injected into the large language model. Utilizing a semantic vector-driven dynamic few-sample retrieval mechanism, the most relevant expert cases are accurately matched under quality scoring filtering and diversity constraints, enhancing the model's ability to learn the task-behavior mapping relationship. The generated results undergo dual syntactic and logical checks by an evaluation operator, and failed results are structured into feedback information containing error type, location, description, and correction suggestions, guiding the model to perform iterative minimization corrections. Finally, a legally usable behavior tree is output and automatically stored in the expert case library to complete the knowledge loop. This technical solution comprehensively solves a series of key problems in behavior tree generation tasks for lightweight large language models, such as high illusion rate, weak resource awareness, lack of expert experience, unstable quality, and high deployment costs, achieving end-to-end, highly stable, evolvable, and low-cost automatic behavior tree generation capabilities.

[0056] Example 2: like Figure 2 As shown, this application provides an automatic behavior tree generation device based on a large language model, the device comprising: The context building module is used to obtain the behavior tree generation request, build a node variable context object containing available node definitions, variable constraint dictionary and agent type information, and build system prompt words and task prompt words based on the node variable context object to realize the structured injection of behavior tree syntax specifications and node resource constraints; The dynamic sample retrieval module is used to convert task description information into semantic vectors, perform cosine similarity calculation based on the semantic vectors and pre-calculated vectors in the expert case library, dynamically filter few sample examples through a Top-K selection algorithm with quality score filtering and diversity constraints, and embed the few sample examples into system prompt words to form complete generated prompt words; The behavior tree generation module is used to call the large language model to generate a behavior tree based on the complete generated prompt words; The evaluation and refinement module is used to perform evaluation operator checks on the generated behavior tree, convert the results of the checks that fail into structured feedback information containing error type, error location, error description and correction suggestions, and construct refinement prompt words based on the structured feedback information to drive the large language model to perform minimization iterative correction; The case accumulation module is used to store the generated results into the expert case library and update the semantic vectors, quality scores and usage statistics of the cases.

[0057] The modules in the aforementioned behavior tree automatic generation device based on a large language model can be implemented entirely or partially through software, hardware, or a combination thereof. These modules can be embedded in or independent of the processor in a computer device, or stored in the memory of a computer device as software, so that the processor can call and execute the operations corresponding to each module.

[0058] This application provides a basic capability foundation by loading default node configuration information, captures personalized needs by extracting user-defined node information, ensures that user control is not overridden by merging user-defined nodes with priority, and guarantees the integrity and traceability of variable constraints through variable dictionary encapsulation. On this basis, the constructed node variable context object can truly reflect the intersection of user intent and system capabilities, providing accurate, complete, and controllable context support for resource constraint injection in this application, thereby improving the legitimacy, usability, and stability of the generated behavior tree.

[0059] Example 3: In one exemplary embodiment, such as Figure 3 As shown, this application provides an electronic device, which can be a server, industrial control computer, edge computing gateway, or robot main control board. The electronic device includes a processor, memory, input / output interfaces (I / O), and a communication interface. The processor, memory, and I / O interfaces are connected via a system bus, and the communication interface is connected to the system bus via the I / O interfaces. The processor of this electronic device provides computing and control capabilities, supports x86, ARM, or RISC-V instruction set architectures, and can call upon GPU acceleration units to collaboratively execute vector computation and large language model inference tasks.

[0060] The electronic device's memory includes a non-volatile storage medium and internal memory. The non-volatile storage medium stores the operating system, computer programs, and a database. The internal memory provides the environment for the operating system and computer programs in the non-volatile storage medium to run. The electronic device's database stores expert case library data, node configuration information, variable constraint dictionaries, semantic vector indexes, and quality scoring tables. The electronic device's input / output interface is used for exchanging information between the processor and external devices. The electronic device's communication interface is used for communicating with external terminals via a network connection, supporting Ethernet, Wi-Fi, 5G, or industrial fieldbus protocols. When the computer program is executed by the processor, it implements an automatic behavior tree generation method based on a large language model.

[0061] Example 4: On the other hand, such as Figure 4 As shown, this application also provides a computer-readable storage medium, which may be included in the electronic device described in the above embodiments, or it may exist independently and not assembled into the electronic device. The computer-readable storage medium stores one or more programs that, when used by one or more processors, execute the behavior tree automatic generation method based on a large language model described in this application.

[0062] It should be noted that the terminology used herein is for the purpose of describing particular embodiments only and is not intended to limit the exemplary embodiments according to this application. As used herein, the singular form is intended to include the plural form as well, unless the context clearly indicates otherwise. Furthermore, it should be understood that when the terms "comprising" and / or "including" are used in this specification, they indicate the presence of features, steps, operations, devices, components, and / or combinations thereof.

[0063] It should be noted that the terms "first," "second," etc., used in the specification, claims, and accompanying drawings of this application are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such terms can be used interchangeably where appropriate so that the embodiments of this application described herein can be implemented in sequences other than those illustrated or described herein.

[0064] Furthermore, the terms “comprising” and “having”, and any variations thereof, are intended to cover non-exclusive inclusion. For example, a process, method, system, product, or apparatus that includes a series of steps or units is not necessarily limited to those steps or units that are explicitly listed, but may include other steps or units that are not explicitly listed or that are inherent to such process, method, product, or apparatus.

[0065] For ease of description, spatial relative terms such as "above," "on top of," "on the upper surface of," "above," etc., are used herein to describe the spatial positional relationship of a device or feature as shown in the figures to other devices or features. It should be understood that spatial relative terms are intended to encompass different orientations in use or operation beyond the orientation of the device as described in the figures. For example, if the device in the figures were inverted, a device described as "above" or "on top of" other devices or structures would subsequently be positioned as "below" or "under" other devices or structures. Thus, the exemplary term "above" can include both "above" and "below." The device may also be positioned in other different ways, such as rotated 90 degrees or in other orientations, and the spatial relative descriptions used herein will be interpreted accordingly.

[0066] In the detailed description above, reference has been made to the accompanying drawings, which form part of this document. In the drawings, similar symbols typically identify similar parts unless the context otherwise indicates otherwise. The illustrated embodiments described in the detailed specification, drawings, and claims are not intended to be limiting. Other embodiments may be used and other changes may be made without departing from the spirit or scope of the subject matter presented herein.

[0067] The above description is merely a preferred embodiment of the present invention and is not intended to limit the invention. Various modifications and variations can be made to the present invention by those skilled in the art. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.

Claims

1. A method for automatically generating behavior trees based on a large language model, characterized in that, include: Obtain a behavior tree generation request, the generation request including task description information, agent type information, and available node configuration information; Construct a node variable context object, which contains the identifier, type, attributes, and port definitions of available nodes, as well as a variable constraint dictionary; Based on the node variable context object and the task description information, system prompt words and task prompt words are constructed. The system prompt words include behavior tree syntax specifications, node writing rules and output format constraints. The task prompt words include agent information, task description and registration node information, realizing resource constraint injection. The task description information is converted into a semantic vector. Cosine similarity is calculated based on the semantic vector and the pre-calculated semantic vector in the expert case library. The few sample examples are dynamically filtered by the Top-K selection algorithm with quality score filtering and diversity constraints. The few sample examples are embedded into the system prompt words to obtain the complete generated prompt words. The large language model is invoked to generate a behavior tree based on the complete generated prompt words, and the evaluation operator is checked on the behavior tree; If the evaluation operator check fails, the check result is converted into structured feedback information, which includes error type, error location, error description and correction suggestions. Based on the structured feedback information, refined prompt words are constructed, and the large language model is called to perform minimum iterative correction on the behavior tree until the evaluation operator check passes or the maximum number of iterations is reached. Output the behavior tree that passes the evaluation, and store the generated results in the expert case library.

2. The method for automatically generating behavior trees based on a large language model according to claim 1, characterized in that, The construction node variable context object includes: Load default node configuration information; Extract user-defined node information from the generated request; Based on the user-defined node priority merging strategy, the default node configuration is merged with the user-defined node; Encapsulate the variable dictionary into the merged node variable context object.

3. The method for automatically generating behavior trees based on a large language model according to claim 1, characterized in that, The Top-K selection algorithm for the diversity constraint includes: Initialize the selected case set; Candidate cases that have passed quality filtering are traversed from high to low based on cosine similarity. Calculate the semantic similarity between the current candidate case and each case in the selected case set; If the similarity between the current candidate case and any selected case is greater than or equal to the diversity threshold, then the current candidate case is skipped; otherwise, the current candidate case is added to the set of selected cases. Repeat the above steps until the number of selected cases reaches the target number K or the candidate cases have been traversed.

4. The method for automatically generating behavior trees based on a large language model according to claim 3, characterized in that, The quality score threshold for the quality filter is 0.6, the diversity threshold is 0.85, and the target quantity K ranges from 3 to 5.

5. The method for automatically generating behavior trees based on a large language model according to claim 1, characterized in that, The evaluation operator checks include syntax checks and logic defect detection; The syntax checks include: root node verification, node structure validity check, node registration verification, node attribute verification, and variable reference validity check; The logic defect detection includes: checking the number of child nodes of the control node according to rules, and checking for meaningless nesting.

6. The method for automatically generating behavior trees based on a large language model according to claim 1, characterized in that, The refined prompt words include refined system prompt words, the original behavior tree, and the structured feedback information; the refined system prompt words define the large language model as a behavior tree correction expert, requiring minimal modification to the original behavior tree, correcting only the problematic parts while retaining other correct content unchanged.

7. The method for automatically generating behavior trees based on a large language model according to claim 1, characterized in that, The large language model is a locally deployed lightweight language model that performs efficient inference through an inference engine framework; the generated parameters include: temperature parameter T is 0.6, Top-p sampling parameter p is 0.95, and the maximum number of output tokens N is 8192.

8. An apparatus for automatically generating behavior trees based on a large language model, employing the behavior tree automatic generation method based on any one of claims 1 to 7, comprising: The context building module is used to obtain the behavior tree generation request, build a node variable context object containing available node definitions, variable constraint dictionary and agent type information, and build system prompt words and task prompt words based on the node variable context object to realize the structured injection of behavior tree syntax specifications and node resource constraints; The dynamic sample retrieval module is used to convert task description information into semantic vectors, perform cosine similarity calculation based on the semantic vectors and pre-calculated vectors in the expert case library, dynamically filter few sample examples through a Top-K selection algorithm with quality score filtering and diversity constraints, and embed the few sample examples into system prompt words to form complete generated prompt words; The behavior tree generation module is used to call the large language model to generate a behavior tree based on the complete generated prompt words; The evaluation and refinement module is used to perform evaluation operator checks on the generated behavior tree, convert the results of the checks that fail into structured feedback information containing error type, error location, error description and correction suggestions, and construct refinement prompt words based on the structured feedback information to drive the large language model to perform minimization iterative correction; The case accumulation module is used to store the generated results into the expert case library and update the semantic vectors, quality scores and usage statistics of the cases.

9. An electronic device, comprising: Memory and processor; The memory stores a computer program, and when the processor executes the computer program, it implements the automatic generation method of behavior tree based on a large language model as described in any one of claims 1 to 7.

10. A computer-readable storage medium having a computer program stored thereon, the computer program, when executed by a processor, implementing the automatic generation method of behavior trees based on a large language model as described in any one of claims 1 to 7.