Dynamic narrative engine system and method based on state variables
By dividing narrative state variables into core, session, and global states, and utilizing hybrid logic judgment and state repair modules to dynamically generate media content, the problems of singular state management and fixed media content in dynamic narrative engines are solved, improving user experience and system usability.
Patent Information
- Application Number
- CN202511495006.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-10-20
- Publication Date
- 2026-01-30
AI Technical Summary
Existing dynamic narrative engines have a single dimension of state management, making it impossible to distinguish between core plot states and temporary conversation states. Condition judgments rely on static rules, lacking the ability to adapt to ambiguous semantics. Furthermore, media content is pre-set and fixed, making it impossible to generate personalized narrative elements in real time.
The state management module divides narrative state variables into core state, session state, and global state. The hybrid logic judgment module performs condition judgment through pre-compiled rules and a lightweight large language model. The state repair module repairs logical conflicts. The media generation module dynamically generates media content.
It achieves efficient recognition of fuzzy semantics and real-time generation of personalized media content, improving user experience and system usability, and solving the problems of single state management and fixed media content.
Smart Images

Figure CN121435977A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of artificial intelligence-driven interactive entertainment technology, and in particular to a dynamic narrative engine system and method based on state variables. Background Technology
[0002] Currently, with the development of the interactive entertainment industry, users have placed higher demands on the personalization, immersion, and replayability of content. Traditional linear narrative modes are no longer sufficient to meet these needs, leading to the emergence of dynamic narrative systems. These systems can alter the plot based on user choices and behaviors, providing unique experiences. However, existing dynamic narrative engines still face several key technical bottlenecks, hindering their large-scale application and further improvement in user experience quality. These include: a single dimension of state management, an inability to distinguish between core plot states and temporary conversational states; reliance on static rules for condition determination, a lack of adaptability to ambiguous semantics; and fixed, pre-defined media content, making it impossible to generate personalized narrative elements in real time. Summary of the Invention
[0003] To address the aforementioned problems, this invention provides a dynamic narrative engine system and method based on state variables to solve the problems mentioned in the background art, such as the single dimension of state management, inability to distinguish between core plot states and temporary conversation states, reliance on static rules for condition determination, lack of adaptability to ambiguous semantics, and fixed pre-set media content, which prevents the generation of personalized narrative elements in real time.
[0004] A dynamic narrative engine system based on state variables is characterized in that the system includes: a state management module, which is used to divide narrative state variables into three logical layers: core state, session state and global state, and execute differentiated storage, update and synchronization strategies based on state type; The hybrid logic decision module is used to determine the deterministic and fuzzy conditions in parallel narrative nodes by a symbolic logic processing unit based on pre-compiled rules and a semantic reasoning unit based on a lightweight large language model. The state repair module is used to determine logical conflicts in the detected narrative path based on the judgment results, and to perform state consistency repair based on the state distance metric and the candidate node replacement algorithm. The media generation module is used to dynamically generate one or more media content, including text, images, and audio, based on the replacement narrative nodes and the current state variables.
[0005] Preferably, the status management module includes: The core state processing submodule uses a sharding strategy and a transactional mechanism to achieve state persistence. Its state update function is as follows:
[0006] in, This represents the global state at time t+1. Let t represent the global state at time t. Represented as state increment; The session state processing submodule is used to implement a high-frequency read / write and session binding mechanism based on memory caching; The global state processing submodule is used to implement concurrent access and state synchronization for multiple users using conflict-free copy data types.
[0007] Preferably, the hybrid logic determination module includes: The pre-filtering submodule is used to initially filter the initial list of narrative nodes using a Bloom filter to obtain a list of candidate narrative nodes; The evaluation submodule is used to perform parallel condition evaluation on each narrative node in the candidate narrative node list and filter out the target narrative node list with parallel flow. The first processing module is used to acquire user input and current state parameters and input them into a preset classifier. The deterministic logic in the classifier is processed by a symbolic logic processing unit based on pre-compiled rules. The second processing module is used to process fuzzy semantics in the classifier through a semantic reasoning unit based on a lightweight large language model, and select the optimal narrative node based on the first processing result and the second processing result.
[0008] Preferably, the state repair module is used to determine logical conflicts in the detected narrative path based on the judgment result, and to perform state consistency repair based on the state distance metric and the candidate node replacement algorithm, including: The prediction submodule is used to predict the narrative state parameters at the next time step t+k based on the optimal narrative node selected by the judgment result. The determination submodule is used to determine the logical conflict index in the narrative path based on the predicted narrative state parameters, and to determine the conflict narrative nodes based on the logical conflict index. Obtain the current state metric of the conflict narrative node, and select the optimal replacement node from the candidate nodes based on the multimodal state distance metric. The state distance function is:
[0009] in, Distribution of entity relationships between narrative nodes This is the state feature extraction function.
[0010] Preferably, the media generation module includes: The cache management submodule is used to obtain the node identifier and current state parameters of the replaced narrative node to generate a cache key, and to query or store the generated media content. The parallel generation submodule is used to concurrently call the large language model service, image generation service, and text-to-speech service to generate dialogue, background images, and audio content simultaneously. The physics simulation submodule is used to call the physics engine to simulate the effects of the generated dialogue, background images, and audio content based on the physical parameters contained in the current state parameters.
[0011] Preferably, the system further includes: a cross-narrative universe state transfer module, used to extract, transform, and verify state data between different narrative systems to achieve the transferability of user states and narrative continuity, specifically including: State features are extracted from the source narrative universe using a feature extraction function, and the extracted state features are mapped to the target narrative universe using a domain adaptation transformation function. The logical consistency of the state characteristics after migration is verified using a consistency check function.
[0012] Preferably, the system further includes a predictive preloading module, used to use an LSTM model to predict the potential narrative state that the user will enter in the future, and to generate media content corresponding to the potential narrative state in advance and store it in the cache.
[0013] Preferably, the domain adaptation transformation function maps the extracted state features to the target narrative universe through a linear transformation matrix, and the step of verifying the logical consistency of the transferred state features through a consistency check function includes: The transferred state feature vector is input into a trained classifier. The classifier outputs a consistency index between 0 and 1. The consistency index is compared with a first verification threshold. When the consistency index is higher than the first verification threshold, the state transfer is preliminarily determined to have passed the consistency verification. Calculate the compatibility score between the migrated state feature vector and the rule constraint vector of the target narrative universe. When the compatibility score is higher than a second preset threshold, it is further determined that the state migration has passed the consistency verification. The system is also used for: When the consistency index falls below the first verification threshold, the state feature backtracking mechanism is triggered to iteratively fine-tune the linear change matrix, remap the state features, and re-evaluate the consistency index. If the consistency index still fails to reach the verification threshold, the state feature migration is deemed to have failed and an alert is issued.
[0014] Preferably, the predictive preloading module uses an LSTM model to predict the potential narrative state that the user will enter in the future, including: Obtain the narrative state vector sequence of the user's most recent n time steps and the prediction step size k. Use the LSTM model to determine the probability distribution of the state in the next k steps based on the narrative state vector sequence of the most recent n time steps. Based on the probability distribution of the future k-step states, the potential narrative state vector with the highest probability is selected to obtain the narrative logic of the potential narrative state vector; Determine the potential narrative states that users will enter in the future based on narrative logic.
[0015] A dynamic narrative method based on state variables includes the following steps: Receive user input and the current narrative state, and update the core state, session state, or global state based on the user input and the current narrative state; The triggering conditions of narrative nodes are evaluated by a hybrid logic judgment engine, and narrative logic conflicts are detected and repaired by the state repair module. The generative media adapter dynamically generates media content corresponding to narrative nodes and states and performs physical simulation. Output a narrative response and update the system state.
[0016] Other features and advantages of the invention will be set forth in the following description, and will be apparent in part from the description, or may be learned by practicing the invention. The objects and other advantages of the invention may be realized and obtained by means of the structures particularly pointed out in the written description and the accompanying drawings.
[0017] The technical solution of the present invention will be further described in detail below with reference to the accompanying drawings and embodiments. Attached Figure Description
[0018] The accompanying drawings are provided to further illustrate the invention and form part of the specification. They are used together with the embodiments of the invention to explain the invention and do not constitute a limitation thereof.
[0019] Figure 1 A schematic diagram of the structure of a dynamic narrative engine system based on state variables provided by the present invention; Figure 2 A schematic diagram of the structure of a hybrid logic determination module in a dynamic narrative engine system based on state variables provided by the present invention; Figure 3 A schematic diagram of the structure of a media generation module in a dynamic narrative engine system based on state variables provided by the present invention; Figure 4 A flowchart illustrating the workflow of a dynamic narrative engine method based on state variables provided by this invention; Figure 5 A flowchart illustrating the hierarchical state update process of system components developed for a dynamic narrative engine system based on state variables according to the present invention. Figure 6A flowchart illustrating the hybrid logic decision-making process of system components developed for a dynamic narrative engine system based on state variables according to the present invention. Figure 7 This is a flowchart illustrating the media generation workflow of the system components developed for a dynamic narrative engine system based on state variables according to the present invention. Detailed Implementation
[0020] Exemplary embodiments will now be described in detail, examples of which are illustrated in the accompanying drawings. When the following description relates to the drawings, unless otherwise indicated, the same numerals in different drawings denote the same or similar elements. The embodiments described in the following exemplary embodiments do not represent all embodiments consistent with this disclosure. Rather, they are merely examples of apparatuses and methods consistent with some aspects of this disclosure as detailed in the appended claims.
[0021] Currently, with the development of the interactive entertainment industry, users have placed higher demands on the personalization, immersion, and replayability of content. Traditional linear narrative modes are no longer sufficient to meet these needs, leading to the emergence of dynamic narrative systems. These systems can alter the plot based on user choices and behaviors, providing unique experiences. However, existing dynamic narrative engines still face several key technical bottlenecks, hindering their large-scale application and further improvement in user experience quality. These include: limited state management dimensions, inability to distinguish between core plot states and temporary conversational states; reliance on static rules for condition determination, lack of adaptability to ambiguous semantics; and fixed, pre-defined media content, making it impossible to generate personalized narrative elements in real time. To address these issues, this embodiment discloses a dynamic narrative engine system based on state variables.
[0022] A dynamic narrative engine system based on state variables, such as Figure 1 As shown, the system includes: The state management module 101 is used to divide the narrative state variables into three logical layers: core state, session state, and global state, and to execute differentiated storage, update, and synchronization strategies based on the state type. The hybrid logic decision module 102 is used to determine the deterministic and fuzzy conditions in parallel narrative nodes by a symbolic logic processing unit based on pre-compiled rules and a semantic reasoning unit based on a lightweight large language model. The state repair module 103 is used to determine the logical conflicts in the detected narrative path based on the judgment result, and to perform state consistency repair based on the state distance metric and the candidate node replacement algorithm. The media generation module 104 is used to dynamically generate one or more media contents, including text, images, and audio, based on the replacement narrative node and the current state variable.
[0023] In this embodiment, state variables are divided into three categories: Core state: stored using CRC32 fragmentation, with the transactional persistence update formula as follows: ; in, Indicates the core state. This represents user input, and ΔG represents the global state increment. Session state: Memory cache, supports high-frequency read and write; Global state: shared across users, driving events; In this embodiment, the lightweight large language model is represented as an artificial intelligence language model trained on massive amounts of text data that consumes little resources and is easy to deploy. In this embodiment, the semantic reasoning unit is represented as a model unit that uses AI to reason about fuzzy semantics; In this embodiment, the session state in the state management module is managed using an LRU eviction policy and a TTL expiration mechanism; the global state is achieved eventually through a conflict resolution algorithm based on vector clocks.
[0024] The working principle of the above technical solution is as follows: First, the narrative state variables are divided into three logical layers—core state, session state, and global state—through the state management module, and differentiated storage, update, and synchronization strategies are executed based on the state type. Second, a hybrid logic judgment module is used to judge the deterministic and fuzzy conditions in parallel narrative nodes based on the symbolic logic processing unit of pre-compiled rules and the semantic reasoning unit of a lightweight large language model. Then, the state repair module determines the logical conflicts in the detected narrative path based on the judgment results, and performs state consistency repair based on the state distance metric and the candidate node replacement algorithm. Finally, the media generation module dynamically generates one or more media contents, such as text, images, and audio, based on the replaced narrative nodes and the current state variables.
[0025] The beneficial effects of the above technical solution are as follows: by dividing multiple state variables, the state type can be quickly distinguished according to the real-time state. Furthermore, by identifying and analyzing the fuzzy conditions of the narrative nodes based on the semantic reasoning unit, the ability to identify fuzzy semantics can be improved through dynamic identification. Furthermore, by determining the narrative path of complete logic and generating real-time personalized media content, the desired media content can be generated according to user needs, improving the user experience and usability. This solves the problems mentioned in the existing technology, such as the single dimension of state management, inability to distinguish between core plot state and temporary conversation state, reliance on static rules for condition judgment, lack of adaptability to fuzzy semantics, and fixed preset media content, which makes it impossible to generate personalized narrative elements in real time.
[0026] In one embodiment, the state management module includes: The core state processing submodule uses a sharding strategy and a transactional mechanism to achieve state persistence. Its state update function is as follows: ; in, This represents the global state at time t+1. Let t represent the global state at time t. Represented as state increment; The session state processing submodule is used to implement a high-frequency read / write and session binding mechanism based on memory caching; The global state processing submodule is used to implement concurrent access and state synchronization for multiple users using conflict-free copy data types.
[0027] The beneficial effects of the above technical solution are as follows: By setting up a core state processing submodule to distribute data across multiple database shards, the horizontal scalability of the system is improved, avoiding single-point bottlenecks, thereby enhancing the system's performance in processing large amounts of core state data. Furthermore, updating via state increment ΔG, rather than full replacement, reduces data transfer volume and storage overhead, improving update efficiency. Additionally, by setting up a session state processing submodule, high-frequency read and write operations can be supported, reducing latency and improving the response speed of user interactions. Associating session states with specific user sessions achieves user state isolation, ensuring the security and independence of each user's state in a multi-user environment. Finally, by setting up a global state processing submodule, multiple users can simultaneously modify the global state without lock contention, improving the system's concurrency performance.
[0028] In one embodiment, such as Figure 2 As shown, the hybrid logic determination module 102 includes: The pre-filtering submodule 1021 is used to initially filter the initial narrative node list using a Bloom filter to obtain a candidate narrative node list; The evaluation submodule 1022 is used to perform parallel condition evaluation on each narrative node in the candidate narrative node list and filter out the target narrative node list with parallel process. The first processing module 1023 is used to acquire user input and current state parameters and input them into a preset classifier, and process the deterministic logic in the classifier through a symbolic logic processing unit based on pre-compiled rules; The second processing module 1024 is used to process fuzzy semantics in the classifier through a semantic reasoning unit based on a lightweight large language model, and select the optimal narrative node based on the first processing result and the second processing result.
[0029] The beneficial effects of the above technical solution are as follows: by filtering the target narrative node list, the number of nodes that need to be accurately evaluated can be quickly reduced, improving the overall performance. Furthermore, by selecting the optimal narrative node, the optimal development narrative node can be selected based on the priority strategy combined with user input and current state parameters, laying the foundation for subsequent dynamic media generation and further improving practicality.
[0030] In one embodiment, the state repair module is used to determine logical conflicts in the detected narrative path based on the judgment result, and to perform state consistency repair based on the state distance metric and the candidate node replacement algorithm, including: The prediction submodule is used to predict the narrative state parameters at the next time step t+k based on the optimal narrative node selected by the judgment result. The determination submodule is used to determine the logical conflict index in the narrative path based on the predicted narrative state parameters, and to determine the conflict narrative nodes based on the logical conflict index. Obtain the current state metric of the conflict narrative node, and select the optimal replacement node from the candidate nodes based on the multimodal state distance metric. The state distance function is: ; in, Distribution of entity relationships between narrative nodes This is the state feature extraction function.
[0031] In this embodiment, logic is represented by a conflict index, which is an evaluation index of the logical conflict in the plot development between various narrative nodes in the narrative path. In this embodiment, a conflict narrative node is represented as two narrative nodes that have a logical conflict in the development of the plot; In this embodiment, the state feature extraction function is the BERT-base extraction function, specifically: ; Where N represents the number of entities in the narrative node, i represents the i-th entity, and BERT-base represents the BERT-base extraction function. Represented as entity triples, Represented as a trainable projection matrix; In this embodiment, It is expressed as the difference in probability distribution between two narrative nodes, measured by the Jensen-Shannon divergence.
[0032] The beneficial effects of the above technical solution are: it can quickly replace narrative nodes according to changes in narrative logic, ensuring a smooth transition of the plot and meeting user expectations, thereby improving user experience and usability.
[0033] In one embodiment, such as Figure 3 As shown, the media generation module 104 includes: The cache management submodule 1041 is used to obtain the node identifier and current state parameters of the replaced narrative node to generate a cache key, and to query or store the generated media content. The parallel generation submodule 1042 is used to concurrently call the large language model service, image generation service and text-to-speech service to generate dialogue, background image and audio content at the same time. The physics simulation submodule 1043 is used to call the physics engine to simulate the effects of the generated dialogue, background images and audio content based on the physics parameters contained in the current state parameters.
[0034] The beneficial effects of the above technical solution are as follows: by generating dialogue, background images and audio content in parallel, users can fully experience the media content, further improving the user experience; furthermore, by performing effect simulation, the high quality and stability of the generated media content can be guaranteed, further improving its practicality.
[0035] In one embodiment, the system further includes: a cross-narrative universe state transition module, used to extract, transform, and verify state data between different narrative systems to achieve the transferability of user states and narrative continuity, specifically including: State features are extracted from the source narrative universe using a feature extraction function, and the extracted state features are mapped to the target narrative universe using a domain adaptation transformation function. The logical consistency of the state characteristics after migration is verified using a consistency check function.
[0036] In this embodiment, the feature extraction function is: ; The domain adaptation transformation function is: ; The consistency check function is: ; The beneficial effects of the above technical solution are: it can ensure a high degree of correlation and data interoperability between various narrative systems, further improving its practicality.
[0037] In one embodiment, the system further includes a predictive preloading module, used to predict the potential narrative state that the user will enter in the future using an LSTM model, and to generate media content corresponding to the potential narrative state in advance and store it in the cache.
[0038] The beneficial effects of the above technical solution are as follows: by adopting the LRU recycling strategy and TTL expiration mechanism for management, the data consistency of concurrent voting can be guaranteed, while also providing a user verification mechanism to prevent duplicate voting, ensuring the uniqueness and integrity of user input. Furthermore, by generating media content in advance, the timeliness of media content generation can be guaranteed.
[0039] In one embodiment, the domain adaptation transformation function maps the extracted state features to the target narrative universe through a linear transformation matrix, and the step of verifying the logical consistency of the transferred state features through a consistency check function includes: The transferred state feature vector is input into a trained classifier. The classifier outputs a consistency index between 0 and 1. The consistency index is compared with a first verification threshold. When the consistency index is higher than the first verification threshold, the state transfer is preliminarily determined to have passed the consistency verification. Calculate the compatibility score between the migrated state feature vector and the rule constraint vector of the target narrative universe. When the compatibility score is higher than a second preset threshold, it is further determined that the state migration has passed the consistency verification. The system is also used for: When the consistency index falls below the first verification threshold, the state feature backtracking mechanism is triggered to iteratively fine-tune the linear change matrix, remap the state features, and re-evaluate the consistency index. If the consistency index still fails to reach the verification threshold, the state feature migration is deemed to have failed and an alert is issued.
[0040] In this embodiment, the trained classifier is represented as a classifier that performs synchronous sameness recognition on state feature vectors. The classifier is a multilayer perceptron, which is trained by a large number of cross-universe state feature pairing samples labeled "compatible" or "incompatible".
[0041] In this embodiment, the rule constraint vector is represented as a text encoding vector of the target narrative universe using a pre-trained language model. It is a mathematical representation of the core rule system of the target narrative universe, which encodes abstract narrative rules into machine-processable feature vectors. In this embodiment, the compatibility score between the transferred state feature vector and the rule constraint vector of the target narrative universe is calculated using cosine similarity.
[0042] The beneficial effects of the above technical solution are: it can comprehensively evaluate the successful transfer of state features between various narrative systems and thus issue effective feedback, thereby improving stability and reliability.
[0043] In one embodiment, the predictive preloading module uses an LSTM model to predict the potential narrative state that a user will enter in the future, including: Obtain the narrative state vector sequence of the user's most recent n time steps and the prediction step size k. Use the LSTM model to determine the probability distribution of the state in the next k steps based on the narrative state vector sequence of the most recent n time steps. Based on the probability distribution of the future k-step states, the potential narrative state vector with the highest probability is selected to obtain the narrative logic of the potential narrative state vector; Determine the potential narrative states that users will enter in the future based on narrative logic.
[0044] In one embodiment, this embodiment also discloses a dynamic narrative method based on state variables, such as... Figure 4 As shown, it includes the following steps: Step S401: Receive user input and current narrative state, and update core state, session state, or global state based on user input and current narrative state; Step S402: Evaluate the triggering conditions of the narrative node through the hybrid logic judgment engine, and detect and repair narrative logic conflicts through the state repair module; Step S403: Dynamically generate media content corresponding to the narrative nodes and states through the generative media adapter and perform physical simulation; Step S404: Output the narrative response and update the system state.
[0045] The working principle and beneficial effects of the above technical solution have been explained in the system embodiments and will not be repeated here.
[0046] In one embodiment, this embodiment discloses a dynamic narrative logic based on state variables, including: (1) Hierarchical state update, such as Figure 5 As shown, 1. Unified state update entry point (StateManager.update) This method serves as the central control center for state updates. It receives a user ID and a state change description (delta), and determines which type of state (core, session, or global) to update based on delta.type. After all state updates are complete, the handle_dependencies method is called to handle any existing state dependencies.
[0047] 2. Core state update (update_core); Core state updates prioritize consistency and persistence, typically involving database operations: 1) Sharding: Data shards (shard_id) are determined by performing a CRC32 hash operation on the user ID and taking the modulo (%256). This is a common horizontal sharding strategy used to distribute load. 2) Transactions: A database transaction is initiated on the determined shard to ensure the atomicity of subsequent operations. 3) Retrieve Current Value: The current core state of the user is retrieved from the transaction. 4) Apply Changes: The new state value is calculated based on the information in delta. 5) Persistence: The new state value is stored in the database. 6) Logging: Detailed information about this state change (who, when, what key, from what value to what value) is logged for auditing or traceability. 7) Global Synchronization: If this core state change affects the global state (delta.affects_global), the global state service is invoked for synchronization.
[0048] 3. Session state update (update_session); Session state updates prioritize speed and temporariness, and are typically stored in a memory cache (such as Redis). 1) Retrieve Session: Retrieve the user's session object from the cache. If it doesn't exist, create a new one. 2) Update Key-Value: Update the value of delta.key in the session object to delta.value. 3) Refresh TTL: Update the session's time-to-live (TTL), usually to keep the session valid while the user remains active.
[0049] 4. Global state update (update_global); The global state is shared by all users, and its updates require handling concurrent conflicts. Conflict-free merging is achieved using CRDT (Conflict-Free Replicated Data Type) technology to merge delta. CRDT is a data structure designed to guarantee that a consistent state will eventually be reached even under concurrent updates, without the need for locks or complex coordination.
[0050] 5. State dependency handling (handle_dependencies); This mechanism maintains consistency between states. When a state changes, all other states that depend on it are automatically updated: 1) Dependency lookup: Using a predefined dependency graph, all other state keys (dependent_keys) that depend on the changed state key (changed_key) are found. 2) Recalculation: For each dependent key, the value of that dependent state is recalculated based on the new data source. 3) Recursive update: A new Delta object is created for the calculated new value, and then the StateManager.update method is recursively called to complete the update. This forms a trigger chain, ensuring that all related states are updated.
[0051] (2) Mixed logic decision, such as Figure 6 As shown: Algorithm step description; Pre-filtering; Objective: To quickly reduce the number of nodes that require precise evaluation and improve overall performance.
[0052] Operation: Use a Bloom filter (bloomFilter.Filter) to perform a preliminary screening of the initial list of nodes. A Bloom filter is a space-efficient probabilistic data structure used to quickly determine whether an element is likely to exist in a set. It may produce false positives (i.e., incorrectly identifying a node as a candidate), but it will not produce false negatives (i.e., it will not incorrectly exclude qualified candidates).
[0053] Output: A preliminary list of candidate nodes (candidateNodes).
[0054] Parallel Conditional Evaluation.
[0055] Objective: To make accurate condition judgments on the initially screened candidate nodes and improve the evaluation speed by using concurrency.
[0056] operate: Create a buffered channel (results) with a capacity equal to the number of candidate nodes (len(candidateNodes)). This allows the senders (goroutines) to send results quickly without blocking.
[0057] Iterate through the candidateNodes list and start a separate goroutine (lightweight thread) for each candidate node.
[0058] Within each goroutine: the hybrid evaluator (hybridEvaluator.Evaluate) is invoked to perform an accurate evaluation of the node (n) and the current user state (userState). This evaluation process may combine reasoning from a rule engine and a lightweight LLM.
[0059] If the evaluation result is true (i.e., the node meets the condition), the node is sent to the results channel. If the evaluation result is false, the goroutine terminates and does not send any content.
[0060] Output: Multiple goroutines concurrently send nodes that meet the criteria to the results channel. Due to concurrent execution, the order in which the evaluations are completed is unpredictable.
[0061] Select the optimal node (OptimalNodeSelection).
[0062] Objective: To select the optimal node from all nodes that pass the condition evaluation, based on a certain priority strategy.
[0063] Operation: The priority selector (prioritySelector.Select) reads all the nodes that have been sent from the results channel. The Select method continues to receive nodes from the channel until there is no more data to process (or according to a timeout or other strategy). Then, it sorts and compares these nodes according to a built-in priority algorithm (e.g., highest weight, best rating, best match to user preference, etc.), and finally returns the optimal node.
[0064] Output: Returns a final Node object as the result of the process.
[0065] Key features and precautions Concurrency Mode: This algorithm uses Go's concurrency primitives goroutines and channels. Goroutines allow for the creation of a large number of concurrent tasks to handle evaluation work at very low cost. Channels are used to safely pass data between goroutines and the main thread, avoiding explicit locking operations.
[0066] Performance and Efficiency: Pre-screening via a Bloom filter avoids costly, precise evaluation of a large number of obviously unsuitable nodes, significantly improving efficiency. Parallel evaluation further leverages the performance of multi-core CPUs, reducing overall response time.
[0067] Result uncertainty: Because the evaluation is parallel, multiple nodes may simultaneously meet the conditions and be placed into the channel. The logic of prioritySelector determines which node will ultimately be selected. If all results are needed, the Select method can be modified to return a list.
[0068] Channel operations: The `results` channel in the code is buffered, meaning that send operations will not block if the buffer is not full, which helps improve concurrency performance. Once all goroutines have finished executing, no new data will be written to the channel.
[0069] (3) Media generation, such as Figure 7 As shown: Algorithm Step Description: Entry Point and Cache Check (render_scene) This method is the main entry point for scene rendering. It receives a node ID and the current state, and returns a MediaPack object containing all generated media.
[0070] Generate cache key: Generate a unique cache key based on node_id and state to identify the current request and ensure that requests on the same node and in the same state can hit the cache.
[0071] Check cache: If caching is enabled (cache_enabled is True) and the cache_key exists in the cache, the MediaPack object in the cache is returned directly, skipping all generation steps and greatly improving performance.
[0072] Create an empty MediaPack: If the cache is missed, a new, empty MediaPack object is created with its node_id set to the current node ID.
[0073] Parallel content generation To maximize efficiency, dialogue, background, and audio generation are performed in parallel.
[0074] Generate Dialogue: This method is called if the current node needs dialogue (needs_dialogue(node_id) is True). It constructs a prompt based on the node ID and state, then uses the Large Language Model Service (llm_service) to generate the dialogue text and assigns it to media_pack.dialogue.
[0075] Generate background (generate_image): This method is called if the current node requires a background image (needs_background(node_id) is True). It also constructs an image generation tooltip, then calls the image generation service (image_service) to generate the URL of the background image and assigns it to media_pack.background.
[0076] Generate audio (generate_audio): This method is called if the current node needs audio (needs_audio(node_id) is True). It first constructs the text to be synthesized, then uses the text-to-speech service (tts_service) to generate the URL of the audio file and assigns it to media_pack.audio.
[0077] Physics simulation (simulate_physics) This is a step executed serially, occurring after all parallel generation tasks.
[0078] Check physics requirements: Determine if the current state contains physics effect parameters (has_physics(state)).
[0079] Perform the simulation: If necessary, the physics engine (physics_engine) is invoked, passing in the physical parameters (state.physics_params) from the state for simulation calculations. The simulation results (which may include data on forces, trajectories, collisions, etc.) are stored in the media_pack.physics dictionary.
[0080] caching and return Write to cache: If caching is enabled, the final generated MediaPack object containing all media content will be stored in the cache with cache_key as the key for subsequent identical requests.
[0081] Return result: Finally, the MediaPack object is returned to the caller.
[0082] Key features and design patterns Adapter Pattern: The design of this class embodies the principles of the adapter pattern. It provides a unified render_scene interface to the outside world, while internally it adapts and coordinates multiple different services (LLM, image generation, TTS, physics engine), "converting" the interfaces of these services into a unified media package output, simplifying external calls.
[0083] Caching strategy: By using a caching mechanism (which may use a database like Redis), the overhead of repeatedly generating the same content is avoided, which is crucial for improving system performance and reducing computing costs.
[0084] Parallel execution: Fully utilizes the capabilities of modern multi-core processors to parallelize independent generation tasks (dialogue, images, audio), significantly reducing overall generation latency.
[0085] Conditional generation: By using conditional judgment functions such as needs_xxx(), on-demand generation is achieved, avoiding unnecessary computation and resource waste, making the system more flexible and efficient.
[0086] Other embodiments of this disclosure will readily occur to those skilled in the art upon consideration of the specification and practice of the disclosure herein. This application is intended to cover any variations, uses, or adaptations of this disclosure that follow the general principles of this disclosure and include common knowledge or customary techniques in the art not disclosed herein. The specification and examples are to be considered exemplary only, and the true scope and spirit of this disclosure are indicated by the following claims.
[0087] It should be understood that this disclosure is not limited to the precise structures described above and shown in the accompanying drawings, and various modifications and changes can be made without departing from its scope. The scope of this disclosure is limited only by the appended claims.
Claims
1. A state variable based dynamic narrative engine system, characterized in that, The system comprises: a state management module for dividing narrative state variables into three logical layers of core state, session state and global state, and performing differentiated storage, update and synchronization strategies based on state types; a hybrid logic judgment module for determining certainty and ambiguity conditions in parallel narrative nodes based on a symbolic logic processing unit of pre-compiled rules and a semantic reasoning unit of a lightweight large language model; a state repair module for determining logical conflicts in a detected narrative path according to a judgment result, and performing state consistency repair based on state distance measurement and candidate node replacement algorithm; a media generation module for dynamically generating one or more media contents of text, image and audio according to a replaced narrative node and current state variables.
2. The dynamic narrative engine system based on state variables of claim 1, wherein, The state management module comprises: The core state processing submodule uses a sharding strategy and a transaction mechanism to realize state persistence, and a state update function thereof is: ; wherein, represents the global state at time t+1, represents the global state at time t, represents the state increment; a session state processing submodule for implementing high-frequency read-write and session binding mechanisms based on memory caching; a global state processing submodule for implementing multi-user concurrent access and state synchronization using conflict-free replicated data types.
3. The dynamic narrative engine system based on state variables of claim 1, wherein, The hybrid logic judgment module comprises: a pre-filtering submodule for obtaining a candidate narrative node list by preliminarily screening an initial narrative node list through a Bloom filter; an evaluation submodule for evaluating conditions of each narrative node in the candidate narrative node list in parallel, and screening a target narrative node list with parallel processes; a first processing module for obtaining user input and current state parameters and inputting them into a preset classifier, and processing deterministic logic in the classifier based on a symbolic logic processing unit of pre-compiled rules; a second processing module for processing fuzzy semantics in the classifier based on a semantic reasoning unit of a lightweight large language model, and selecting an optimal narrative node according to first processing results and second processing results.
4. The dynamic narrative engine system based on state variables of claim 1, wherein, The state repair module is configured to determine logical conflicts in a detected narrative path according to a judgment result, and perform state consistency repair based on state distance measurement and candidate node replacement algorithm, and comprises: a prediction submodule for predicting narrative state parameters at a future time t+k according to an optimal narrative node selected according to a judgment result; a determination submodule for determining a logical conflict index in a narrative path according to predicted narrative state parameters, and determining a conflict narrative node based on the logical conflict index; obtaining a current state measurement of the conflict narrative node, and selecting an optimal replacement node from candidate nodes based on the current state measurement according to a multi-modal state distance measurement, and a state distance function is: ; wherein, is an entity relationship distribution between narrative nodes, is a state feature extraction function.
5. The dynamic narrative engine system based on state variables of claim 1, wherein, The media generation module comprises: a cache management submodule for generating a cache key by obtaining a node identifier and current state parameters of a replaced narrative node, and querying or storing generated media contents; a parallel generation submodule for concurrently calling a large language model service, an image generation service and a text-to-speech service to simultaneously generate dialogues, background images and audio contents; a physical simulation submodule for calling a physical engine to simulate effects of generated dialogues, background images and audio contents according to physical parameters contained in current state parameters.
6. The dynamic narrative engine system based on state variables of claim 1, wherein, The system further comprises a cross-narrative universe state migration module for extracting, converting and verifying state data between different narrative systems, realizing the migratability of user state and narrative continuity, specifically comprising: extracting state features from the source narrative universe through a feature extraction function, and mapping the extracted state features to the target narrative universe through a domain adaptation transformation function; verifying the logical consistency of the migrated state features through a consistency verification function.
7. The dynamic narrative engine system based on state variables according to claim 1, characterized in that, the system further comprises a predictive preloading module for predicting the potential narrative state that the user will enter in the future using an LSTM model, and generating the media content corresponding to the potential narrative state in advance and storing it in the cache.
8. The dynamic narrative engine system based on state variables of claim 6, wherein, The domain adaptation transformation function maps the extracted state features to the target narrative universe through a linear change matrix, and the consistency verification function verifies the logical consistency of the migrated state features, including: inputting the migrated state feature vector into a trained classifier, outputting a consistency index between 0 and 1 through the classifier, comparing the consistency index with the first verification threshold, and preliminarily determining that the state migration passes the consistency verification when the consistency index is higher than the first verification threshold; calculating the compatibility score between the migrated state feature vector and the rule constraint vector of the target narrative universe, and further determining that the state migration passes the consistency verification when the compatibility score is higher than the second preset threshold; the system is further used for: when the consistency index is lower than the first verification threshold, triggering a state feature backtracking mechanism, iteratively fine-tuning the linear change matrix, remapping the state features, and reevaluating the consistency index, and if the subsequent consistency index still cannot reach the verification threshold, determining that the state feature migration fails and issuing a reminder.
9. The dynamic narrative engine system based on state variables of claim 6, wherein, The predictive preloading module uses an LSTM model to predict the potential narrative state that the user will enter in the future, including: obtaining the narrative state vector sequence of the user in the last n time steps and the prediction step length k, using the LSTM model to determine the future k-step state probability distribution according to the narrative state vector sequence of the last n time steps; selecting the potential narrative state vector with the highest probability based on the future k-step state probability distribution, obtaining the narrative logic of the potential narrative state vector; determining the potential narrative state that the user will enter in the future according to the narrative logic.
10. A dynamic narrative method based on state variables, characterized in that, including the following steps: receiving user input and current narrative state, updating core state, session state or global state according to user input and current narrative state; evaluating the trigger condition of the narrative node through the hybrid logic judgment engine, and detecting and repairing the narrative logic conflict through the state repair module; dynamically generating and physically simulating the media content corresponding to the narrative node and state through the generative media adapter; outputting the narrative response and updating the system state.