An AI-assisted narrative content generation system and method based on a story world ledger

By using an AI-assisted narrative content generation system based on a story world ledger, and leveraging the SPO triple storage and time sequence detection module, the system solves the problem of long narrative consistency relying on context windows, achieves independent structured storage and consistency assurance, and improves logical consistency and rule compliance.

CN122433904APending Publication Date: 2026-07-21BEIJING ZHIBO LINGXI TECHNOLOGY CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202610548964.2
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-04-23
Publication Date
2026-07-21

AI Technical Summary

Technical Problem

In existing AI-assisted narrative content generation technologies, the consistency of long narratives relies on context windows, which is structurally unreliable. Constraint rules are coupled with the generation process and lack an independent verification mechanism, leading to consistency collapse and a decrease in constraint compliance rate.

Method used

An AI-assisted narrative content generation system based on a story world ledger is adopted. The system persistently stores the facts of the story world through SPO triples, and uses a time-series detection module and a verification constraint module to achieve independent structured storage and consistency assurance. Combined with a multi-round self-repair mechanism, an automatic closed loop of generation-verification-repair is formed.

Benefits of technology

It ensures the certainty and consistency of long narratives, avoids information loss and logical contradictions, and improves logical consistency and rule compliance.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122433904A_ABST
    Figure CN122433904A_ABST
Patent Text Reader

Abstract

The application relates to the field of artificial intelligence natural language processing and content generation, and discloses an AI-assisted narrative content generation system and method based on a story world ledger, which stores story facts in the form of SPO triplets through a ledger storage module, carries time validity range, severity level marks and causal pointers to realize structured state tracing; a time sequence detection module automatically distinguishes time sequence conflicts of facts with the same subject-predicate and different objects and overlapping time, and blocks or warns according to the severity level; a verification constraint module independent of the generation process performs hard constraint formal verification and soft constraint guided inspection, and cooperates with a multi-round self-repairing module to inject violation details into the next round of system prompt words and restart the cycle engine to guide self-repairing to form a closed loop when verification fails; a three-sublayer maintenance module divides hard facts, state tracking and creation intention sublayers, and a cycle engine classifies and executes side-effect-free tools in parallel, so that the consistency and rule compliance of long narrative are improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of artificial intelligence natural language processing and content generation technology, and in particular to an AI-assisted narrative content generation system and method based on a story world ledger. Background Technology

[0002] Currently, there are two main technical solutions in the field of AI-assisted narrative content generation. The first is the direct generation solution using a general-purpose large language model, represented by ChatGPT (OpenAI) and Claude (Anthropic). Users request the model to generate story content through natural language dialogue commands. All story world states—including character settings, relationships, timeline events, and world rules—exist only within the model's context window and are not stored in an independent structured manner. The second is AI writing assistance tools, represented by NovelAI's Lorebook mechanism and Sudowrite's Story Bible mechanism. NovelAI uses a keyword-triggered mechanism; when preset keywords appear in the generated text, the system automatically injects the corresponding settings into the large language model context. Sudowrite maintains a structured story setting document containing fields such as type, style, story synopsis, characters, world construction, and outline, and injects this document content each time the large language model is invoked.

[0003] The aforementioned and existing related technologies suffer from the following drawbacks: Firstly, the story world state relies entirely on the context window of the large language model as its sole carrier. When the narrative content exceeds the window's capacity, information such as the character's state, relationships, and item ownership established earlier is lost, leading to inconsistencies such as character state contradictions and causal breaks in the timeline. Existing solutions' passive setting injection or unidirectional information flow cannot guarantee structured consistency. Secondly, constraint rules are injected using natural language prompts, relying entirely on the model's "self-compliance," resulting in a decrease in constraint compliance rate as the context grows. Furthermore, it is impossible to independently and formally detect and automatically block constraint violations. Summary of the Invention

[0004] The technical problem to be solved by this invention is that existing technologies have the disadvantages of relying on context windows for consistency in long narratives, resulting in unreliable structure. At the same time, the constraint rules are coupled with the generation process and lack an independent verification mechanism. To address this, we propose an AI-assisted narrative content generation system and method based on a story world ledger.

[0005] To achieve the above objectives, this application adopts the following technical solution: an AI-assisted narrative content generation system based on a story world ledger, comprising: a ledger storage module: used to persistently store the facts of the story world in SPO triples, each fact record containing a subject, predicate, object, fact type, severity marker, time validity start number, time validity end number, substitution relationship pointer, and causal relationship pointer, realizing the structured storage and tracing of the story world state independent of the context window; a time sequence detection module: used to compare whether the time validity ranges of two facts with the same subject and the same predicate in the story world ledger overlap, and when the time ranges overlap and the objects are different, it is determined to be a time sequence conflict, and the generation process is blocked or a warning message is recorded according to the severity marker of the conflicting facts; three sub-layers The maintenance module is used to divide the story world ledger into three differentiated sub-layers: a hard fact sub-layer, a state tracking sub-layer, and a creative intent sub-layer. The validation constraint module operates independently of the large language model generation process, performing hard constraint formal validation and soft constraint guided checks on the generated content. The loop engine module executes a reasoning-action-observation loop, calling the large language model in each loop to obtain reasoning results and tool call requests. After parsing the tool call requests, it categorizes tools with and without side effects and delivers them to the parallel tool module and serial execution logic processing, respectively. The multi-round self-repair module injects violation details into the next round's system prompt when the constraint validation module returns failure details and the current number of attempts has not reached the maximum number of attempts, restarting the ReAct loop engine to guide the large language model to self-repair and generate content.

[0006] Preferably, the system also includes: a concentric growth module: used to define six concentric growth rings from the seed ring to the text ring, setting a target set of fact types and a minimum density threshold for each growth ring, adding facts to the world ledger through expansion operations, generating formatted documents from ledger facts through projection operations, and extracting emergent facts from the generated text and supplementing them to the ledger through reconciliation operations, thus realizing the progressive structured construction of the story world; a parallel tool module: used to receive side-effect-free tool call requests parsed by the ReAct loop engine, simultaneously launching all side-effect-free tools using a concurrent execution mechanism, waiting for completion through Promise all Settled, and returning results through an event stream according to the actual completion order of the tools, regardless of the submission order; and an SSE event module: used to define a structured event set containing at least 30 event types, assigning a monotonically increasing sequence number to each event, pushing the event from the server to the client through the SSE protocol, and having the client detect lost events based on the sequence number and resume from the last processed sequence number after network reconnection.

[0007] Preferably, the system further includes: a skill combination module: used to independently manage creative knowledge according to eight levels, dynamically combine and load knowledge levels by triggering gating condition expressions and intent-aware gating, and output the total token amount of the combined knowledge to the budget truncation module; a budget truncation module: used to receive the total token amount of knowledge output by the skill combiner, and when the value exceeds the preset budget, truncate the knowledge content in order of hierarchical priority from low to high until the total token amount is not higher than the budget, and return a truncation status flag; a context engineering module: used to divide the input context of the large language model into four independent planes: identity policy plane, conversation state plane, task context plane, and evidence context plane, allocate the token budget of each plane according to the main intent type output by the hybrid intent classifier, and execute the independent assembly strategy of each plane; and a format-aware co-creation module: used to read format-independent core facts from the hard fact sub-layer of the story world ledger, load the hard constraint set and soft constraint set of the target format, inject the native creative knowledge of the target format through the skill combiner, and drive the large language model to generate format-native narrative content under the triple input of core facts, format constraints, and format knowledge.

[0008] Preferably, the six concentric growth rings are arranged in a progressive order from seed to main text as seed ring, core ring, setting ring, outline ring, set outline ring, and main text ring; wherein: the seed ring uses entity, constraint, and intent as target fact types, with a minimum density threshold of at least 1 entity fact (the existence of the main character), 1 constraint fact (world rule or pressure), and 1 intent fact (story direction). After meeting the criteria, a logline is generated through the PROJECT operation; the core ring uses attribute character features and relation character relationships as target fact types, with a minimum density threshold of at least 3 entities each having more than 1 attribute fact and at least 2 relation facts connecting entities. After meeting the criteria, a character card is output through the PROJECT operation;

[0009] The setting loop targets fact types based on intent (character goals and motivations), style (style), and relationship (character relationships). The minimum density threshold is that all main characters have intent, attribute, and relationship coverage, and at least one style fact defines the tone. Once this is achieved, the story setting document (Story Bible) is output via the PROJECT operation, triggering mandatory user review gating. The outline loop targets fact types based on events (major events) and structure (act / chapter structure). The minimum density threshold is that each act has at least one event fact and one structure fact defining the act boundary, with characters having curved positions defined at the act boundary. Once this is achieved, the story outline is output via the PROJECT operation. The episode outline loop targets fact types refined to the scene level, specifically events and states. The minimum density threshold is at least two event facts per episode and at least one state change for each main character per episode. Once this is achieved, the episode outline is output via the PROJECT operation. The main text loop does not add new fact types; it generates the original main text or script format from the episode's fact set, including style and constraint facts, through the PROJECT operation. After completion, emergent facts are extracted to supplement the ledger via the RECONCILE operation.

[0010] Preferably, the ledger storage module includes: an SPO triplet storage module: used to store each fact record in a subject-verb-object structure, where each fact record contains a subject field, a verb field, and an object field. A fact type classification module: used to categorize each fact into a unique type among nine mutually exclusive complete types: entity, attribute, relation, state, event, structure, constraint, intent, and style. A time series range management module: used to assign a valid From Ordinal field and a valid Until Ordinal field to each fact, recording the valid start and end positions of the fact in the scene sequence number. A causal tracing module: used to set a caused By field for each fact pointing to the event ID that triggered the fact, and a supersedes field pointing to the old fact ID that was replaced by this fact.

[0011] Preferably, the three differentiated sub-layers of the three-layer maintenance module are as follows: The hard facts sub-layer uses structured JSON or relational database storage. The AI ​​agent automatically extracts new facts from the output text after each content generation, and persists them after deduplication by matching with existing facts using SPO triples. It stores objective facts including character entities, event records, timeline nodes, world rules, and relationships between entities. The state tracking sub-layer uses a hybrid storage of structured JSON and natural language annotations. The AI ​​agent proposes state change proposals based on the generated content, which are then written into the ledger after user confirmation. It stores semi-structured information including character emotional state, trust relationship quantification value, character knowledge scope, and character current location. The creative intent sub-layer uses pure natural language storage. It only accepts direct editing by the creator and prohibits modification by the AI ​​system. It is only injected into the context of the large language model as a generation constraint. It stores pure creative level information including theme goals, emotional arc planning, and style taboos.

[0012] Preferably, the constraint verification module includes: a hard constraint formal verification module, used to perform deterministic judgments on the word count limit, format structure, role survival status logic, and causal consistency of the timeline of the generated content, and immediately block the generation process if any hard constraint is not met; a soft constraint guided verification module, used to inject flexible rules into the context of the large language model in the form of skill knowledge, guide the large language model to perform self-checks on the generated content and output a self-evaluation report, without blocking the generation process; and a conflict fact arbitration module, used to receive conflict fact pairs output by the temporal conflict detection module, and decide whether to block the generation process or record a warning message based on the severity field value of the conflict fact.

[0013] Preferably, the loop engine module includes: a context compression trigger module: used to replace early tool call results with summary text when the message history length exceeds 50 messages, retaining key information; a plan signal parsing module: used to parse the HTML annotation format plan step status markers embedded in the large language model output, extracting step identifiers and status values; a tool call extraction module: used to parse the tool_use block from the large language model output, extracting tool names, input parameters, and call identifiers; and a loop termination detection module: used to check for user cancellation signals, timeout signals, and safety blocking signals at the beginning of each loop, terminating the loop immediately upon receiving any of these signals.

[0014] Preferably, the execution flow of the loop engine module is as follows: Step 1: Check for abort signals. If a user cancellation signal, timeout signal, or safety blocking signal is received, the loop is terminated. Step 2: Emitter a turn_progress event, carrying the current turn number. Step 3: Determine if the message history length exceeds 50 messages. If so, perform context compression, replacing the results of earlier tool calls with summary text to retain key information. Step 4: Call the large language model, supporting streaming and non-streaming modes. In streaming mode, incremental text is pushed to the client in real time via the text_delta event, while extended thinking content is pushed separately via the thinking_start, thinking_delta, and thinking_end events. Step 5: Parse the HTML annotation format plan step status markers embedded in the output of the large language model. The marker format is plan. Step 6: Extract the `tool_use` block from the large language model output as a tool call request. Step 7: If there is no tool call request, emit the final text event to end the current loop. Step 8: Execute the tool call, classifying tools into parallelizable tools and tools that must be executed sequentially. Parallelizable tools are non-interactive tools without side effects. All parallelizable tools are started simultaneously through a concurrent execution mechanism. An independent execution Promise is created for each tool, and all Promises are settled to wait. Results are returned through an event stream according to the actual completion order of the tools. Tools that must be executed sequentially are tools with side effects or require user interaction. They are executed strictly in order to ensure atomicity. Step 9: Collect all tool execution results (`tool_result` blocks) and append them to the message history. Step 10: Return to Step 1 to continue the next loop.

[0015] Preferably, the present invention provides another technical solution: an operation method for an AI-assisted narrative content generation system based on a story world ledger, comprising the following implementation steps: S1: The system completes user login authentication, the user creates a new project and inputs a story concept in the left navigation bar, and the ledger storage module initializes a story world ledger instance; S2: The system receives the user's natural language creation instructions in the dialogue input area, the loop engine module starts the ReAct loop, and the SSE event module pushes output through a streaming protocol; when the task involves multiple steps, a structured execution plan is automatically generated; S3: The context engineering module determines the user's idea graph through a hybrid intent classifier and allocates token budgets for four context planes; S4: The concentric growth module sequentially executes the EXPAND operations of the seed ring, core ring, and setting ring to generate character entities, attributes, relationships, and style facts; after the setting ring is completed, a mandatory user review gating is triggered, and the user passes through the three-sub-layer maintenance module... The creative intent sub-layer injects creative intent; S5: The concentric growth module executes the outline loop EXPAND operation, adding events and structural facts. After reaching the density threshold, the PROJECT operation is executed to output the story outline; S6: The concentric growth module executes the set outline loop EXPAND operation, generating scene-level events and character state changes episode by episode in scene order. After reaching the density threshold, the PROJECT operation is executed to output the episode outline; S7: The concentric growth module executes the text loop PROJECT operation. The format-aware co-creation module loads the target format constraints and format knowledge to generate the format native script text; the constraint verification module performs hard constraint verification, triggering multiple rounds of self-repair modules when not satisfied; after completion, the RECONCILE operation is executed, and the emergent facts are written into the ledger through the ledger storage module.

[0016] The technical effects and advantages of this invention are as follows: This invention uses a ledger storage module to persistently store story world facts in SPO triples, carrying time validity ranges, substitution relationship pointers, and causal relationship pointers. This allows key narrative elements such as character states, character relationships, and event causality to no longer rely solely on the context window of a large language model as their sole carrier. Instead, they form a structured, traceable, and auditable persistent ledger independent of the generation process. Simultaneously, a time-series detection module automatically identifies temporal overlap and object differences in facts with identical subjects and predicates. When inconsistencies such as contradictory character states, conflicting item ownership, or timeline breaks are detected, timely blocking or warnings are issued based on the severity, thereby achieving determinism in long narratives. Consistency is guaranteed, completely avoiding information loss and logical contradictions caused by context window sliding. In addition, this invention sets up a verification constraint module that runs independently of the large language model generation process. It performs hard constraint formal verification and soft constraint guided checks on the generated content. With the help of a multi-round self-repair module, when verification fails, the violation details are injected into the next round of system prompts and the ReAct loop engine is restarted, forming an automatic closed loop of "generation-verification-repair". This improves the constraint compliance from relying on the model to "self-consciously" to the formal detection and automatic correction of an independent module. It solves the defects of constraint rules decaying with the growth of context and being unable to be detected and blocked independently, which significantly improves the logical consistency and rule compliance of long narrative generation. Attached Figure Description

[0017] The disclosure of this invention is illustrated with reference to the accompanying drawings. It should be understood that the drawings are for illustrative purposes only and are not intended to limit the scope of protection of this invention. In the drawings, the same reference numerals are used to refer to the same parts:

[0018] Figure 1 This is a system architecture diagram of an AI-assisted narrative content generation system and method based on a story world ledger, according to the present invention. Figure 2 This is a system logic diagram of an AI-assisted narrative content generation system and method based on a story world ledger, according to the present invention. Figure 3 This is an architecture diagram of the ledger storage module of an AI-assisted narrative content generation system and method based on a story world ledger according to the present invention; Figure 4 This is a diagram of the loop engine module architecture of an AI-assisted narrative content generation system and method based on a story world ledger according to the present invention. Figure 5 This is a constraint verification module architecture diagram of an AI-assisted narrative content generation system and method based on a story world ledger according to the present invention. Detailed Implementation

[0019] It is readily understood that, based on the technical solution of this invention, those skilled in the art can propose various interchangeable structural methods and implementations without altering the essential spirit of the invention. Therefore, the following detailed embodiments and accompanying drawings are merely illustrative examples of the technical solution of this invention and should not be considered as the entirety of the invention or as limitations or restrictions on the technical solution of this invention.

[0020] Reference Figures 1-5 As shown, this invention provides a technical solution: an AI-assisted narrative content generation system based on a story world ledger, comprising, from bottom to top: a story world ledger layer, a constraint verification layer, and an LLM creative generation layer. The connection between the three layers is as follows: the LLM creative generation layer reads factual data from the story world ledger layer as the generation context; the constraint verification layer independently verifies the constraints of the LLM output and feeds back the verification results to the LLM creative generation layer to trigger self-repair. The overall system architecture is as follows:

[0021] The ledger storage module is the data core of the entire system, used to persistently store all the facts of the story world. This module uses SPO (Subject-Predicate-Object) triples as the basic storage structure. Each fact record contains the following fields: Subject: The main entity of the fact, such as a character name, location, or item; Predicate: Describes the relationship or action between the subject and object, such as "resides in," "knows," or "owns"; Object: The object of the fact, such as a specific location, another character, or item attributes; Fact Type: Classifies facts into one of nine types: entity, attribute, relation, state, event, structure, constraint, intent, or style; Severity: Used to determine the importance level of the fact during time-series conflict detection, including critical, major, and minor levels; Valid From Ordinal: The scenario number in which the fact begins to take effect; Valid Until Ordinal: The scenario number in which the fact ends to take effect; Supersedes: Points to the ID of the superseded fact when it is replaced by a new fact; Caused: Points to the causal relationship. By): When a fact is caused by an event, it points to the event ID that triggered the fact.

[0022] This structured storage method allows the state of the story world to be persistently stored and traced independently of the context window of the large language model. When new narrative content needs to be generated, the system can query relevant factual information from the ledger without relying on previously generated context.

[0023] The timing detection module works closely with the ledger storage module to detect timing conflicts in the story world. The specific detection logic is as follows: The system compares two fact records in the ledger that have the same subject and predicate. First, it checks if their time validity ranges overlap. If the time ranges overlap, it further determines if the objects of the two facts are the same. If the time ranges overlap but the objects are different, it is determined to be a timing conflict.

[0024] For example, suppose the ledger contains the following two facts: Fact A: Subject = "Zhang San", Verb = "Located at", Object = "Beijing", Time validity = [1, 5]; Fact B: Subject = "Zhang San", Verb = "Located at", Object = "Shanghai", Time validity = [3, 8]. Since the time validity ranges [1, 5] and [3, 8] of the two facts overlap (the overlapping interval is [3, 5]), and the objects are different (Beijing vs. Shanghai), the system determines that there is a timing conflict. The timing detection module will perform corresponding operations based on the severity of the conflicting facts: if the severity is marked as critical or major, the subsequent generation process is blocked; if it is minor, only a warning message is recorded and the generation process is allowed to continue.

[0025] The three-layer maintenance module divides the story world ledger into three sublayers with different properties and access permissions: The hard facts sublayer uses structured JSON or a relational database for storage, recording objective and verifiable facts of the story world. The AI ​​agent automatically extracts new facts from the output text after each content generation, performs deduplication comparison with existing facts using SPO triple matching, and persists them to this sublayer. The hard facts sublayer stores the following content: character entities (e.g., "Zhang San", "Li Si"), event records (e.g., "Zhang San turns eighteen"), timeline nodes (e.g., "Event XX will occur in 2070"), world rules (e.g., "Magic cannot be used in public"), and relationships between entities (e.g., "Zhang San is Li Si's father").

[0026] The state tracking sublayer uses a hybrid storage method combining structured JSON and natural language annotations to record semi-structured state information of characters in the story world. AI agents propose state change suggestions based on the generated content, but these proposals require user confirmation before being written to the ledger. The state tracking sublayer stores the following content: character emotional state (e.g., "Zhang San feels frustrated"), trust relationship quantification (e.g., "Zhang San's trust level with Li Si is 70"), character knowledge scope (e.g., "Zhang San knows Wang Wu is an undercover agent"), and character current location (e.g., "Zhang San is located in the castle's living room").

[0027] The Creative Intent sublayer uses pure natural language storage to record the creator's creative intentions and constraints for the story. This sublayer has the highest priority access control, allowing only direct editing by the creator; the AI ​​system has no right to modify it. The content stored in the Creative Intent sublayer is injected as constraints into the context of the large language model during the generation process, guiding the generation direction. Stored content includes: thematic goals (e.g., "This story explores the cost of XX"), emotional arc planning (e.g., "The first act is light and cheerful, the second act is tense and oppressive, and the third act is tragic and moving"), and stylistic taboos (e.g., "Illegal and inappropriate descriptions are prohibited").

[0028] The constraint verification module operates independently of the large language model generation process and is used to perform constraint checks on the generated content. This module consists of three sub-modules: the hard constraint formal verification module performs deterministic rule checks on the generated content, including: word count limit checks (ensuring the generated content is within a preset word count range), format and structure checks (ensuring it conforms to script format requirements, such as dialogue format, scene description format, etc.), character survival status logic checks (ensuring characters whose scenes have ended do not reappear), and timeline causal consistency checks (ensuring the order of events conforms to causal logic). When any hard constraint is not met, this module immediately blocks the generation process and returns failure details to the loop engine module.

[0029] The soft constraint-guided verification module injects flexible rules into the context of the large language model in the form of skill knowledge. These flexible rules do not have mandatory judgment capabilities, but rather guide the large language model to perform self-checks during the generation process. For example, injecting "check whether the dialogue conforms to the character's personality traits" as a soft constraint into the context will cause the large language model to refer to this constraint when generating dialogue, but it will not stop generating due to possible non-compliance. This module also receives the self-evaluation report output by the large language model for subsequent analysis.

[0030] The conflict fact arbitration module receives conflict fact pairs output by the timing detection module and determines the handling method based on the severity field value of the conflict fact. Severe conflicts (severity=critical or major) will block the generation process, requiring the user or AI agent to resolve the conflict before continuing; minor conflicts (severity=minor) will only record a warning message, allowing the generation process to continue but retaining the conflict record for subsequent review.

[0031] The loop engine module is responsible for executing the ReAct (Reasoning-Acting-Observation) loop, which is the core mechanism for AI-assisted generation in this system.

[0032] The workflow of the loop engine module is as follows: Step 1: At the beginning of each loop, the loop termination detection module checks for user cancellation signals, timeout signals, or safety blocking signals. If any termination signal is present, the loop terminates immediately. Step 2: The `turn_progress` event is emitted, carrying the current loop number. Step 3: The context compression trigger module determines whether the current message history length exceeds 50 messages. If it does, this module replaces earlier (older) tool call results with summary text, retaining key information while reducing token usage. This mechanism ensures that the system does not experience attention decay due to excessively long context when processing long narratives. Step 4: The large language model call supports both streaming and non-streaming modes. In streaming mode, incrementally generated text is pushed to the client in real time via the `text_delta` event; extended thinking content of the large language model (such as the reasoning process) is pushed separately via the `thinking_start`, `thinking_delta`, and `thinking_end` events. Step 5: The plan signal parsing module parses the HTML comment format plan step status markers embedded in the large language model output. The tag format is "", where X is the step identifier and status is the status value (active indicates in progress, done indicates completed, skipped indicates skipped). This mechanism enables the system to track and update the execution status of multi-step tasks. Step Six: The tool call extraction module parses the tool_use block from the output of the large language model, extracting the tool name, input parameters, and call identifier. Step Seven: If the parsing result does not contain a tool call request, the final text event is emitted, ending the current loop. Step Eight: If a tool call request exists, the system categorizes it into two types: non-interactive tools without side effects and tools that may have side effects or require user interaction. Tools without side effects are delivered to the tool parallel module for concurrent execution; tools with side effects or requiring user interaction are delivered to the serial execution logic for sequential execution. Step Nine: After the tool execution is complete, all tool execution results (tool_result block) are appended to the message history, and then the system enters the next loop.

[0033] The multi-round self-repair module works in conjunction with the validation constraint module and the loop engine module to achieve automatic repair of generated content. When the validation constraint module returns failure details, the multi-round self-repair module checks whether the current number of attempts has reached the maximum number of attempts (configurable, default is 3). If the maximum number has not been reached, the multi-round self-repair module injects the violation details (specifically which constraints were not met, the degree of violation, etc.) into the next round's System Prompt, and then restarts the ReAct loop engine to guide the large language model to repair the specific problem. If the maximum number of attempts has been reached and validation is still not passed, the system will stop the self-repair process and output a failure report for manual processing.

[0034] The concentric growth module is the core component of this system for implementing progressive, structured story construction. This module defines six concentric growth rings, each corresponding to a different stage of story construction, with clearly defined target fact types and minimum density thresholds.

[0035] The seed ring (Ring 0) is the starting point for story construction, aiming to establish the basic concepts of the story. This ring targets three fact types: entity, constraint, and intent. The minimum density threshold requires at least one entity fact (the protagonist exists), one constraint fact (world rules or pressures), and one intent fact (story direction). When the facts in the ledger meet the minimum density threshold, the system executes the PROJECT operation, generating a Logline (a one-sentence summary of the story) from the fact set. The Logline typically contains three core elements: protagonist, conflict, and goal, such as "A lone detective must find the kidnapper within an hour, or his daughter will be in danger."

[0036] The core ring (Ring 1) further refines role information based on the seed ring. This ring targets two fact types: attributes and relationships. The minimum density threshold requires that at least three entities each have at least one attribute fact and at least two relationship facts connecting the entities. When the minimum density threshold is met, the system executes the PROJECT operation to output role cards. Role cards contain detailed attribute descriptions for each main role, their relationship network with other roles, and a summary of their personality traits.

[0037] The Setting Ring (Ring 2) further refines the story's world-building and character motivations. This ring targets three fact types: intent (character goals and motivations), style, and relationship (character relationships). The minimum density threshold requires that all main characters have intent + attribute + relationship coverage (i.e., each main character has goals and motivations, attributes, and relationships with other characters), and at least one style fact defines the story's tone. When the minimum density threshold is met, the system executes the PROJECT operation to output the Story Bible, which contains information such as world-building, historical background, core themes, style, and detailed character profiles.

[0038] Once the ring is set up, a mandatory user review gating is triggered. Before proceeding with further builds, the system must wait for the creator to confirm and review the Story Bible. Creators can inject or modify creative intentions through the creative intention sub-layer; these intentions will act as constraints affecting the subsequent generation process.

[0039] The Ring3 outline breaks down the story into acts and chapters. This ring targets two fact types: events and structures. The minimum density threshold requires that each act has at least one event fact and one structure fact defining the act boundary, and that characters have defined arc positions at the act boundaries (i.e., the character's state changes at the beginning and end of the act are clearly defined). When the minimum density threshold is met, the system executes the PROJECT operation to output the story outline. The outline is organized by act, with each act containing information such as the act's main events, character arcs, and emotional development.

[0040] The Ring4 further refines the outline into episode outlines. This ring aims to refine the event and state fact types to the scene level. Minimum density thresholds require at least two event facts per episode and at least one state change for each main character per episode. When the minimum density thresholds are met, the system executes the PROJECT operation to output episode outlines. Episode outlines are organized by episode, with each episode containing information such as scene settings, event sequences, character state changes, and dialogue highlights.

[0041] The Ring 5 is the final stage of story construction and does not add new fact types. This ring purely generates the formatted native text or script from the episode's fact set (including style and constraint facts) through the PROJECT operation. After the text generation is complete, the system performs a RECONCILE operation to extract "emergent facts" (i.e., new facts that naturally arise during the generation process, such as the appearance of new characters, the establishment of new relationships, etc.) from the generated text and adds these emergent facts to the ledger to ensure the continuous accumulation and consistency maintenance of the story world.

[0042] The three core operations of the Concentric Growth Module are defined as follows: EXPAND Operation: Adds facts to the world ledger. This operation receives user input (such as natural language creation instructions) or AI-generated content, parses and extracts factual information, and writes it to the corresponding sub-layer according to the fact type. When adding a fact, the system automatically assigns a time validity range (default starts from the current scene number, set to infinite validity until explicit termination), a causal relationship pointer (pointing to the event that triggered the fact), and a substitution relationship pointer (initially null). PROJECT Operation: Generates a formatted document from ledger facts. This operation queries the ledger for matching fact records based on the target fact type of the current growth loop, and formats them into a target document (such as Logline, character card, Story Bible, outline, episode outline, script text, etc.) according to a preset template. The projection operation does not modify the ledger content; it only reads and transforms it. RECONCILE Operation: Extracts emergent facts from the generated text and adds them to the ledger. This operation analyzes the AI-generated narrative text, identifies implicit factual information (such as the first appearance of a new character, changes in character relationships, and the occurrence of events), and writes the extracted facts into the ledger. The reconciliation operation is a key mechanism for enabling the story world to "self-evolve," allowing the ledger content to be continuously enriched as it is generated.

[0043] The parallel tool module receives side-effect-free tool call requests parsed by the loop engine module and launches all side-effect-free tools simultaneously using a concurrent execution mechanism. Specifically, the system creates an independent execution Promise for each side-effect-free tool. These tools include, but are not limited to: ledger query tools (reading facts from the ledger storage module), fact verification tools (checking the existence of specific facts), format checking tools (validating text format), and rule matching tools (checking whether content conforms to specific rules). All side-effect-free tools are executed in parallel via the Promise.allSettled mechanism, independent of the commit order.

[0044] After a tool completes its execution, the system returns results via an event stream in the order they were completed. This means that if tool A is submitted earlier but executes more slowly, and tool B is submitted later but executes more quickly, the system will return the result of tool B first, and then return the result of tool A. This design improves the overall response speed of the system and prevents the entire process from being blocked due to the slow execution of a single tool.

[0045] For tools with side effects (such as writing to the ledger, calling external APIs, sending notifications, etc.), the system adopts a serial execution logic, strictly executing them one by one in order to ensure the atomicity of the operation and data consistency.

[0046] The SSE event module defines a structured event set containing at least 30 event types, and pushes events from the server to the client via the SSE (Server-Sent Events) protocol. SSE is a one-way communication protocol based on HTTP, suitable for real-time push scenarios.

[0047] Event type classifications include:

[0048] Loop progress event turn_start, turn_progress, turn_end Text generation event text_start, text_delta, text_chunk, text_end Thinking process events thinking_start, thinking_delta, thinking_end Tool execution events tool_call_start, tool_call_progress, tool_call_end, tool_result Verification event validation_start, validation_progress, validation_pass, validation_fail Ledger Incident ledger_update, ledger_query_result Conflict conflict_detected, conflict_resolved Error events error_warning、error_critical Progress Events step_start, step_progress, step_complete Complete event generation_complete, generation_aborted

[0049] Each event is assigned a monotonically increasing sequence number. The client maintains the highest sequence number of received events. When the network is interrupted and reconnected, the client sends the last processed sequence number as a resume point, and the server re-pushes lost events from that sequence number onwards. This mechanism ensures that the client can receive all events completely, even under unstable network conditions.

[0050] The context engineering module divides the input context of a large language model into four independent planes, each with a different functional role and an independent token budget.

[0051] The Identity Strategy Plane includes system identity definitions, role settings, and behavioral guidelines. This plan defines the AI ​​assistant's role (e.g., "a professional story creation assistant"), the behavioral guidelines to be followed (e.g., "respecting the user's creative intent" and "not arbitrarily modifying the content of the creative intent sub-layer"), and output style requirements (e.g., "using professional terminology" and "maintaining objectivity and neutrality"). The Identity Strategy Plane typically accounts for 10%-15% of the overall Token budget.

[0052] The session state plane contains metadata about the current session, historical interaction summaries, and current task status. This plane records session start time, completed growth loops, currently executing steps, user feedback summaries, and other information related to the session process. The session state plane typically accounts for 5%-10% of the overall token budget.

[0053] The task context plane contains a detailed description of the current task, objectives, constraints, and other relevant information. This plane obtains information directly related to the specific task from the concentric growth module, including information about the current growth cycle, the user's recent creation instructions, and confirmed creation intentions. The task context plane typically accounts for 30%-40% of the overall token budget, making it the largest of the four planes.

[0054] The evidence context plane contains relevant facts retrieved from the ledger storage module, background information of the current scene, character state snapshots, and other content. This plane provides factual basis for the generation process, ensuring that the generated content is consistent with the existing settings of the story world. The evidence context plane typically accounts for 35%-45% of the overall token budget.

[0055] The workflow of the context engineering module is as follows: First, the hybrid intent classifier analyzes the user's natural language input to determine the user's idea graph type (such as "modify character settings", "continue the plot", "query the ledger", etc.); then, the token budget of the four planes is dynamically allocated according to the idea graph type (for example, if the idea graph is to continue the plot, the budget ratio of the task context plane and the evidence context plane is increased); finally, according to the independent assembly strategy of each plane, the content is filled into the corresponding plane to form a complete input context.

[0056] The skill combination module manages creative knowledge independently in eight levels. These eight levels include: basic grammar level (punctuation, paragraph format), script format level (scene marking, dialogue format), narrative skills level (perspective selection, pacing control), character development level (personality modeling, language style), genre norms level (specific rules for genres such as suspense / science fiction / romance), world construction level (magic system, technological settings, etc.), theme expression level (symbolic techniques, theme deepening), and originality protection level (plagiarism prevention check rules).

[0057] The skill combination module dynamically loads knowledge layers by triggering gating condition expressions and intent-aware gating. For example, when the user intent is detected as "generate a suspenseful scene," the system automatically loads suspense-related knowledge from the type specification layer; when magic combat is detected, magic system knowledge from the world-building layer is additionally loaded. The total amount of combined knowledge tokens is output to the budget truncation module.

[0058] The budget truncation module receives the total number of knowledge tokens output by the skill combiner. When this number exceeds the preset budget, the module truncates knowledge content sequentially from lowest to highest priority. The priority order is the reverse of the eight-level arrangement, with the originality protection layer having the highest priority and the basic syntax layer having the lowest. During truncation, the system prioritizes retaining higher-priority knowledge content until the total number of tokens does not exceed the budget. After truncation is complete, the module returns a truncation status flag indicating which levels were partially or completely truncated.

[0059] The format-aware co-creation module is a key component for achieving "format-native" content generation. Its workflow is as follows: First, it reads format-independent core facts from the hard fact sub-layer of the story world ledger, including character information, event sequences, scene settings, and other content-related information that doesn't involve format. Then, it loads the target format's hard and soft constraint sets. The hard constraint set contains mandatory format requirements, such as "the script format must use the scene tag format 'scene number.scene name'" and "dialogue must use the format 'character name: dialogue content'." The soft constraint set contains recommended format guidelines, such as "it is recommended that each dialogue not exceed 5 rounds" and "it is recommended that scene descriptions be kept within 50 words." Next, it injects native creative knowledge of the target format through a skill combiner, including specific writing techniques, common patterns, and classic examples for that format. Finally, it drives the large language model to generate format-native narrative content under three inputs: core facts provide the story content, the format constraint set specifies the format rules that must be followed, and format knowledge provides guidance on how to write well in that format. This triple input mechanism ensures that the generated content not only conforms to the story's internal logic and meets the requirements of the target format, but also possesses the professional standards of that format.

[0060] This invention also provides an operation method for an AI-assisted narrative content generation system based on a story world ledger, including the following implementation steps: S1: System initialization and project creation. After the system completes user login authentication, the user creates a new project and inputs a story concept in the left navigation bar. The story concept can be a one-sentence summary, a text description, or a list of key elements. The ledger storage module initializes the story world ledger instance, creates an empty fact storage structure, and automatically creates initial fact records based on the story concept. Specifically, the system first creates meta-information such as story_id (unique story identifier), created_at (creation time), and updated_at (last update time). Then, it extracts entity-type facts (main characters, important locations / items in the world setting), constraint-type facts (rules or pressures in the story background), and intent-type facts (the initial direction or goal of the story) from the user-input story concept. These initial facts are written into the hard fact sub-layer.

[0061] S2: Receives creation instructions and initiates the ReAct loop; the user sends natural language creation instructions in the dialogue input area, such as "Help me design a villain's backstory" or "Continue writing the adventure plot of Chapter 3." Upon receiving the instructions, the loop engine module initiates the ReAct loop. The SSE event module begins pushing output events via a streaming protocol. In streaming mode, the text increment generated by the large language model is pushed to the client in real time via the text_delta event; if the large language model outputs extended thinking content, it is pushed separately via the thinking_start / thinking_delta / thinking_end events. When the task involves multiple steps (e.g., "create a character card and generate an opening dialogue"), the system automatically generates a structured execution plan. The plan signal parsing module tracks the execution status of the plan, marking the completion status of each step using HTML annotation format.

[0062] S3: Context Engineering and Token Budget Allocation. The context engineering module analyzes the user's natural language input using a hybrid intent classifier to determine the user's idea graph type. Based on the idea graph type, the context engineering module allocates token budgets for four context planes and executes independent assembly strategies for each plane. For example, if the idea graph is "create a character card," the task context plane will emphasize the requirements and templates for character design, the evidence context plane will retrieve existing character information from the ledger (if any), the identity strategy plane will emphasize the professional standards for character building, and the session state plane will record the current task progress.

[0063] S4: The concentric growth module sequentially executes the EXPAND operations for the seed ring, core ring, and setting ring. In the seed ring stage, the system generates fact records of type entity, constraint, and intent through the EXPAND operation. When the ledger contains at least one entity fact (protagonist exists), one constraint fact (world rules or pressure), and one intent fact (story direction), the minimum density threshold is met, and the system executes the PROJECT operation to generate the Logline.

[0064] In the core ring phase, the system generates fact records of type attribute (character traits) and relation (character relationships) through the EXPAND operation. When at least three entities each have more than one attribute fact and at least two relation facts connecting the entities, the minimum density threshold is met, and the system executes the PROJECT operation to output the character card. In the setting ring phase, the system generates fact records of type intent (character goal motivation), style, and relation (character relationships) through the EXPAND operation. When all major characters have intent + attribute + relation coverage and at least one style fact defining the tone, the minimum density threshold is met, and the system executes the PROJECT operation to output the Story Bible. After the setting ring is completed, the system triggers a mandatory user review gating. Creators inject or modify creative intents through the creative intent sub-layer of the three-layer maintenance module. These creative intents will serve as constraints, affecting the subsequent generation process.

[0065] S5: The Concentric Growth Module executes the outline loop. The Concentric Growth Module performs the EXPAND operation on the outline loop, generating fact records of type event (major event) and structure (act / chapter structure). Based on the settings in the Story Bible, the system divides the story into several acts, defining the main events and structural boundaries for each act. Within each act, the arc positions of characters at the beginning and end of the act are explicitly defined. When each act has at least one event fact and one structure fact defining the act boundary, and characters have arc positions defined at the act boundary, the minimum density threshold is met, and the system executes the PROJECT operation to output the story outline.

[0066] S6: The concentric growth module executes the set outline loop. The concentric growth module performs the EXPAND operation of the set outline loop, generating fact records of event and state types refined to the scene level. The system generates scene-level events and character state changes episode by episode in sequence. When each episode has at least two event facts and each main character has at least one state change, the minimum density threshold is met, and the system executes the PROJECT operation to output the episode outline.

[0067] S7: Text Generation, Constraint Verification, and Self-Repair. The concentric growth module executes the PROJECT operation of the text loop. At this point, the format-aware co-creation module plays a crucial role: this module reads format-independent core facts from the hard fact sub-layer, loads the hard and soft constraint sets of the target format, injects native creative knowledge of the target format through the skill combiner, and drives the large language model to generate the native script text under triple input. During the generation process, the constraint verification module runs independently. The hard constraint formal verification module performs deterministic judgments on the generated content, including word count limits, format structure, character survival status logic, and causal consistency of the timeline. If any hard constraint is not met, the generation process is immediately halted. When constraint verification fails, the multi-round self-repair module is activated. This module injects violation details into the next round of system prompts, restarts the ReAct loop engine, and guides the large language model to self-repair specific issues. The self-repair loop executes a maximum of 3 times (configurable). If verification still fails after 3 attempts, the system outputs a failure report for manual processing. After text generation is complete, the system executes the RECONCILE operation. The ledger storage module extracts emergent facts from the generated text and adds them to the ledger. These emergent facts include: newly introduced characters, newly established relationships, the subsequent impact of events, and changes in character states. Through the RECONCILE operation, the story world ledger is continuously updated and enriched, providing a more complete factual basis for subsequent generation.

[0068] The detailed workflow of the time-series detection module is as follows: Step A: Triggering conditions; Time-series detection is triggered in the following situations: 1. When new facts are written to the ledger (whether through an EXPAND or RECONCILE operation). 2. When a user query request is received (such as querying the status of a role at a specific point in time). 3. When a global consistency check is performed after content generation is completed.

[0069] Step B: Algorithm Detection; For each pair of fact records with the same subject and the same predicate, the system performs the following checks: Let the time validity range of fact A be [fromA, untilA]; let the time validity range of fact B be [fromB, untilB]; if (fromA <= untilB) and (fromB <= untilA): # Time range overlap; if A.object != B.object: # Different objects; This is determined to be a time sequence conflict.

[0070] Step C: Conflict Handling; Based on the severity of the conflict (marked by the severity field), the system executes different handling strategies: severity = critical: Immediately halt the current generation process, report the conflict details to the user, and wait for user confirmation of the handling plan before continuing. severity = major: Record a conflict warning message, attach it to the generation context as a constraint, but allow the generation process to continue. Mark potential conflict points in the generated results for subsequent user review. severity = minor: Only record in the conflict log, do not halt the generation process, and do not attach it to the generation context.

[0071] Example of conflict resolution: When a timing conflict is detected, the system can provide the following solutions: 1. Time range adjustment: Modify the time validity range of one of the conflicting facts to eliminate overlap. 2. Fact substitution: Mark the old fact as "substituted" (pointing to the new fact via the supersedes field), retaining the historical record but invalidating it. 3. Fact merging: If the two conflicting facts actually describe different expressions of the same state, merge them into one fact. 4. Manual adjudication: Submit the conflict to the user, who will determine which fact should be retained.

[0072] The ReAct loop of the loop engine module is the core execution mechanism of this system. The detailed implementation is as follows: Loop initialization; Before each ReAct loop begins, the system performs the following initializations: 1. Check if the loop termination detection module 540 has received a termination signal; 2. Initialize the current round counter (turn_counter = 0); 3. Prepare message history (including systemprompt, user commands, and historical interactions); Round execution flow: A specific example illustrates the complete process: Assume the user command is "Help me create three main character cards".

[0073] Round 1: turn_counter = 1; Message history length check: If less than 50 messages, skip context compression; Call the large language model and output: "I need to understand your basic thoughts on these three main characters. Please answer: 1. What is the relationship between these three main characters? 2. What type of story do you want? 3. Are there any special character design requirements?"; Parse the tool_use block: No tool call request; Emit the final text event and end the loop.

[0074] Round 2: User replies: "One is a brave XX (identity / profession), one is a mysterious XX (identity / profession), and one is a retired XX (identity / profession). They are old friends. The story is a suspense type." turn_counter = 2; Call the large language model, output the thought process (push via thinking event) and text: "Understood. I will now start creating the character card." Parse the tool_use block: Found tool_use requests; tool_use_1: create_fact, {type: "entity", name: "XX (identity / profession) Zhang Mou"}; tool_use_2: create_fact, {type: "attribute", subject: "Zhang Mou", predicate: "has", object: "brave"}; tool_use_3: create_fact, {type: "relation", subject: "Zhang Mou", predicate: "is", object: "Li Mou's old friend"}; ... (more tool calls); The tool parallel module receives all tool calls without side effects (such as create_fact) and executes them concurrently; After the tool execution is complete, collect the tool_result block and append it to the message history.

[0075] Round 3 and subsequent loops: The system continues to call the large language model to generate character card content. The process of tool call → execution → result collection is repeated. The loop continues until the output of the large language model no longer contains tool_use requests, indicating task completion.

[0076] Context compression mechanism: When the message history length exceeds 50 messages, the context compression trigger module performs the following operations: Identify the tool_result block (tool execution result) in the message history; for each tool_result, extract key information to generate a summary: Original: {"tool": "create_fact", "result": "Successfully written to the ledger, fact_id: 12345, type: entity, content: XX (identity / occupation) Zhang Mou"}; Compressed: "[Ledger writing] entity fact 12345: XX (identity / occupation) Zhang Mou"; Replace the original tool_result block with the summary; Retain key user commands and system prompts; Through this compression mechanism, the system can significantly reduce token usage while maintaining key information, avoiding attention decay of large language models.

[0077] Stop signal processing: The loop stop detection module can receive the following stop signals: User cancellation signal: The user actively clicks the "Cancel" button or sends a "Cancel" command; Timeout signal: The loop execution time exceeds the preset threshold (default 30 minutes); Security blocking signal: The content security review module detects illegal content; Upon receiving any stop signal, the system immediately stops the loop and saves the current state to the session state plane for subsequent recovery.

[0078] Example 1: Original Micro-Drama Script Generation. Implementation Environment: The server runs Node.js / Bun runtime, uses a PostgreSQL database to store the story world ledger, calls the large language model through the Anthropic Claude API, and the front end is a Next.js web application that receives event streams through SSE.

[0079] Step 1 (Ring 0 Seed Expansion): The creator inputs a one-sentence story concept: "XX falls in love with an independent female protagonist, but the female protagonist is actually an undercover agent for his business rival." The system calls LLM to perform the EXPAND operation, generating 3 initial facts—[entity / hard] Su is a protagonist / undercover agent; [constraint / hard] dual identity creates core dramatic tension; [intent / soft] theme explores love vs. loyalty. The system checks the Ring 0 density threshold (≥1 entity + ≥1 constraint + ≥1 intent), and if satisfied, executes the PROJECT operation to generate the Logline.

[0080] Step 2 (Ring 1-2 World Construction): The system executes the EXPAND operation ring by ring to generate character entities (Lu, Zhou, Lin) and their attributes, relationships, and intentions. After Ring 2 is completed, the system enforces a mandatory user review gate—the creator confirms the character settings and modifies "Lu's background to XXXX," and the system updates the relevant facts and records the changes through the supersedes field. The creator writes their creative intention in sub-layer 1c: "The story's tone is urban emotional suspense, with light and darkness intertwined."

[0081] Step 3 (Ring 3 Outline Generation): The system loads L0 strategy layer skills (creative behavior instructions) and L3 subject matter layer skills (urban suspense depth techniques), and executes EXPAND to generate four acts (introduction, development, climax, and conclusion) of events and structural facts. The constraint verification module checks the coherence of the character arc at the boundaries of each act. After review by the creator, adjustments are made: "The transition pace is too fast; the identity revelation should be more gradual." The system adds three intermediate discovery events.

[0082] Step 4 (Ring4 Episode Outline Development): Develop the episodes sequentially. First, process the "beginning" (episodes 1-25). The system generates scene-level events, character state changes, and hook endings for each episode. After each episode outline is generated, the ReAct loop engine performs constraint verification—a timing conflict detection algorithm checks for overlap between the time ranges of new facts and existing facts to ensure there are no contradictions.

[0083] Step 5 (Ring 5 Text Generation): Taking episode 3 as an example. The system retrieves all relevant facts for episode 3 from the world ledger (character's current state, episode events, hook requirements), loads the micro-drama format constraints (1000-1500 words per episode, minimal dialogue with priority given to actions), and injects style knowledge through the skill combiner. The ReAct loop engine calls the LLM to generate the script text. After generation, the constraint verification module performs a word count check (hard constraint) and a character dialogue style consistency check (soft constraint). If the word count exceeds the limit, a verification failure message is injected into the system prompt for regeneration. After successful verification, the RECONCILE operation extracts emergent facts from the text (such as "Su unconsciously smiled in this episode" as a new state fact record), removes duplicates from existing facts, and writes them into the ledger.

[0084] The effect of this embodiment: During the generation of 100 episodes of scripts, the character states maintained structured tracking across all 100 episodes, without any consistency breakdowns caused by context window sliding. Ring 2's mandatory user review ensured that the creator's intent was accurately captured. The RECONCILE mechanism captured approximately 15% of emergent facts, supplementing narrative details not covered by the original EXPAND.

[0085] Example 2: Conversion of a short drama to a novel format from the same IP. Step 1: Based on the story world ledger completed in Example 1, the creator selects "Output as Novel Format". The system reads all Layer 1a hard facts (character settings, event timeline, world rules) and Layer 1c creative intent from the world ledger.

[0086] Step 2: The skill combiner unloads the micro-drama format knowledge (L2 layer) and loads the novel format knowledge (such as "inner monologues can be developed in depth", "descriptions can be delicate and rich", "chapter length 3000-5000 words") and corresponding format constraints.

[0087] Step 3: The system performs a PROJECT operation on the same set of facts. LLM generates novel chapters in the original format under the framework of "core world facts + novel format constraints + novel creation knowledge".

[0088] The effect of this embodiment: The character settings, event sequence, and world rules are completely consistent with the short drama version (sharing Layer 1a hard facts), but the narrative expression is in the original novel style (richer inner monologues, more detailed scene descriptions, and different chapter structures). There is no need to manually rearrange the character settings and plot structure.

[0089] Example 3: Automatic Recovery from Long-Term Task Interruption. Step 1: The creator requests the generation of all 100 episode outlines (Ring 4), which is expected to require 20 ReAct loops. The system sets the round budget to 8 rounds.

[0090] Step 2: Upon reaching the 8th round (35 episode outlines completed), the system triggers `max_turns_budget_exhausted` to stop. The execution continuity controller writes a checkpoint, including the execution cursor (current Ring 4, 35 episodes completed, next episode is 36) and a compressed summary.

[0091] Step 3: The system detects that the reason for the stop is max_turns_budget_exhausted and resumable is true, and automatically creates a resumed run. The input for the resumed run is the execution cursor in the checkpoint + compressed digest + next step contract ("continue generating the set outline from episode 36 onwards"), without replaying the full message history of the first 8 rounds.

[0092] Step 4: Resume generation from episode 36 onwards. The writing tool uses idempotent key checks to avoid repeatedly writing outlines of completed episodes. If the maximum number of resume attempts (K) is reached, the system pauses and requests user confirmation to continue.

[0093] The effect of this embodiment is that the user does not need to manually enter the "continue" command, and the system automatically resumes from the breakpoint. The context size during continuation is O(1) (compressed digest + cursor) instead of O(n) (full history), avoiding context explosion.

[0094] The technical scope of this invention is not limited to the content described above. Those skilled in the art can make various modifications and variations to the above embodiments without departing from the technical concept of this invention, and all such modifications and variations should fall within the protection scope of this invention.

Claims

1. An AI-assisted narrative content generation system based on a story world ledger, characterized in that, include: The ledger storage module persistently stores the facts of the story world in SPO triples. Each fact record includes a subject, predicate, object, fact type, severity marker, time validity start number, time validity end number, substitution pointer, and causal pointer, enabling structured storage and tracing of the story world state independent of the context window. The time sequence detection module compares the time validity ranges of two facts with the same subject and predicate in the story world ledger to see if they overlap. If the time ranges overlap but the objects are different, it is determined to be a time sequence conflict, and the conflicting facts are marked according to their severity. The system can block the generation process or record warning messages; a three-layer maintenance module is used to divide the story world ledger into three differentiated sublayers: a hard fact sublayer, a state tracking sublayer, and a creative intent sublayer; a verification constraint module is used to run independently of the large language model generation process, performing hard constraint formal verification and soft constraint guided checks on the generated content; a loop engine module is used to execute a reasoning-action-observation loop, calling the large language model in each loop to obtain reasoning results and tool call requests, parsing the tool call requests, classifying tools with and without side effects into those with side effects, and then delivering them to the tool parallel module and serial execution logic processing respectively; Multi-round self-healing module: When the constraint verification module returns failure details and the current number of attempts has not reached the maximum number of attempts, the violation details are injected into the next round of system prompt words, and the ReAct loop engine is restarted to guide the large language model to self-heal and generate content.

2. The AI-assisted narrative content generation system based on a story world ledger as described in claim 1, characterized in that: The system also includes: a concentric growth module: defining six concentric growth rings from the seed ring to the text ring, setting a target set of fact types and a minimum density threshold for each growth ring, adding facts to the world ledger through expansion operations, generating formatted documents from ledger facts through projection operations, and extracting emergent facts from the generated text and supplementing them to the ledger through reconciliation operations, thus achieving a progressively structured construction of the story world; a parallel tool module: receiving side-effect-free tool call requests parsed by the ReAct loop engine, simultaneously launching all side-effect-free tools using a concurrent execution mechanism, waiting for completion through Promise all Settled, and returning results through an event stream according to the actual completion order of the tools, regardless of the submission order; and an SSE event module: defining a structured event set containing at least 30 event types, assigning a monotonically increasing sequence number to each event, pushing events from the server to the client through the SSE protocol, and having the client detect lost events based on the sequence number and resume from the last processed sequence number after network reconnection.

3. The AI-assisted narrative content generation system based on a story world ledger as described in claim 2, characterized in that: The system further includes: a skill combination module: used to independently manage creative knowledge according to eight levels, dynamically combine and load knowledge levels by triggering gating condition expressions and intent-aware gating, and output the total token amount of the combined knowledge to the budget truncation module; a budget truncation module: used to receive the total token amount of knowledge output by the skill combiner, and when the value exceeds the preset budget, truncate the knowledge content in order of hierarchical priority from low to high until the total token amount is not higher than the budget, and return a truncation status flag; a context engineering module: used to divide the input context of the large language model into four independent planes: identity policy plane, conversation state plane, task context plane, and evidence context plane, allocate the token budget of each plane according to the main intent type output by the hybrid intent classifier, and execute the independent assembly strategy of each plane; and a format-aware co-creation module: used to read format-independent core facts from the hard fact sub-layer of the story world ledger, load the hard constraint set and soft constraint set of the target format, inject the native creative knowledge of the target format through the skill combiner, and drive the large language model to generate format-native narrative content under the triple input of core facts, format constraints, and format knowledge.

4. The AI-assisted narrative content generation system based on a story world ledger according to claim 2, characterized in that: The six concentric growth rings, arranged progressively from seed to main text, are: Seed Ring, Core Ring, Setting Ring, Outline Ring, Summary Ring, and Main Text Ring. Specifically: The Seed Ring targets entities, constraints, and intentions as fact types, with a minimum density threshold of at least one entity fact (protagonist existence), one constraint fact (world rule or pressure), and one intention fact (story direction). Upon achieving these thresholds, a Logline is generated via a PROJECT operation. The Core Ring targets attributes and relationships as fact types, with a minimum density threshold of at least three entities each having more than one attribute fact and at least two relationship facts connecting entities. Upon achieving these thresholds, character cards are output via a PROJECT operation. The Setting Ring targets intentions, styles, and relationships as fact types, with a minimum density threshold of all main characters having intent + attribute + relationship coverage and at least one style fact defining the tone. Upon achieving these thresholds, a Story setting document is output via a PROJECT operation. The Bible is used to trigger mandatory user review gating; the outline ring uses events and structure chapters as target fact types, with a minimum density threshold of at least one event fact and one structure fact per act defining the act boundary and defining the character's arc position at the act boundary. After meeting these criteria, the story outline is output through the PROJECT operation; the episode outline ring uses events and states refined to the scene level as target fact types, with a minimum density threshold of at least two event facts per episode and at least one state change for each main character per episode. After meeting these criteria, the episode outline is output through the PROJECT operation; the main text ring does not add new fact types, but generates the original main text or script from the episode's fact set, including style and constraint facts, through the PROJECT operation. After completion, the emergent facts are extracted to supplement the ledger through the RECONCILE operation.

5. The AI-assisted narrative content generation system based on a story world ledger according to claim 1, characterized in that: The ledger storage module includes: an SPO triplet storage module for storing each fact record in a subject-verb-object structure, where each fact record contains a subject field, a verb field, and an object field; a fact type classification module for classifying each fact into a unique type among nine mutually exclusive complete types: entity, attribute, relation, state, event, structure, constraint, intent, and style; a time series range management module for assigning a valid From Ordinal field and a valid Until Ordinal field to each fact, recording the valid start and end positions of the fact in the scene sequence number; and a causal tracing module for setting a caused By field for each fact pointing to the event ID that triggered the fact, and setting a supersedes field pointing to the old fact ID that was replaced by the fact.

6. The AI-assisted narrative content generation system based on a story world ledger according to claim 1, characterized in that: The three differentiated sub-layers of the three-layer maintenance module are as follows: The hard facts sub-layer uses structured JSON or relational database storage. The AI ​​agent automatically extracts new facts from the output text after each content generation, and persists them after deduplication by matching with existing facts using SPO triples. It stores objective facts including role entities, event records, timeline nodes, world rules, and relationships between entities. The state tracking sub-layer uses a hybrid storage of structured JSON and natural language annotations. The AI ​​agent proposes state change proposals based on the generated content, which are then written into the ledger after user confirmation. It stores semi-structured information including role emotional state, trust relationship quantification value, role knowledge scope, and role current location. The creative intent sub-layer uses pure natural language storage, allowing only direct editing by creators and prohibiting AI system modifications. It is injected into the context of the large language model only as a generation constraint, storing pure creative level information including theme goals, emotional arc planning, and style taboos.

7. The AI-assisted narrative content generation system based on a story world ledger according to claim 1, characterized in that: The constraint verification module includes: a hard constraint formal verification module, used to perform deterministic judgments on the word count limit, format structure, role survival status logic, and causal consistency of the timeline of the generated content, and immediately block the generation process if any hard constraint is not met; a soft constraint guided verification module, used to inject flexible rules into the context of the large language model in the form of skill knowledge, guide the large language model to perform self-checks on the generated content and output a self-evaluation report, without blocking the generation process; and a conflict fact arbitration module, used to receive conflict fact pairs output by the temporal conflict detection module, and decide whether to block the generation process or record a warning message based on the severity field value of the conflict fact.

8. The AI-assisted narrative content generation system based on a story world ledger according to claim 3, characterized in that: The loop engine module includes: a context compression trigger module, used to replace early tool call results with summary text while retaining key information when the message history length exceeds 50 messages; a plan signal parsing module, used to parse the HTML annotation format plan step status markers embedded in the large language model output, and extract the step identifier and status value; a tool call extraction module, used to parse the tool_use block from the large language model output, and extract the tool name, input parameters, and call identifier; and a loop termination detection module, used to check for user cancellation signals, timeout signals, and safety blocking signals at the beginning of each loop, and terminate the loop immediately upon receiving any of these signals.

9. The AI-assisted narrative content generation system based on a story world ledger according to claim 8, characterized in that: The execution flow of the loop engine module is as follows: Step 1: Check for abort signals. If a user cancellation signal, timeout signal, or safety blocking signal is received, the loop is terminated. Step 2: Emitter a turn_progress event, carrying the current round number. Step 3: Determine if the message history length exceeds 50 messages. If so, perform context compression, replacing the results of earlier tool calls with summary text to retain key information. Step 4: Call the large language model, supporting streaming and non-streaming modes. In streaming mode, incremental text is pushed to the client in real time via the text_delta event, while extended thinking content is pushed separately via the thinking_start, thinking_delta, and thinking_end events. Step 5: Parse the HTML annotation format plan step status markers embedded in the output of the large language model. The marker format is plan. Step 6: Extract the `tool_use` block from the large language model output as a tool call request. Step 7: If there is no tool call request, emit the final text event to end the current loop. Step 8: Execute the tool call, classifying tools into parallelizable tools and tools that must be executed sequentially. Parallelizable tools are non-interactive tools without side effects. All parallelizable tools are started simultaneously through a concurrent execution mechanism. An independent execution Promise is created for each tool, and all Promises are settled to wait. Results are returned through an event stream according to the actual completion order of the tools. Tools that must be executed sequentially are tools with side effects or require user interaction. They are executed strictly in order to ensure atomicity. Step 9: Collect all tool execution results (`tool_result` blocks) and append them to the message history. Step 10: Return to Step 1 to continue the next loop.

10. The operation method of an AI-assisted narrative content generation system based on a story world ledger according to claim 9, characterized in that: The implementation steps include: S1: The system completes user login authentication. The user creates a new project and enters a story concept in the left navigation bar. The ledger storage module initializes the story world ledger instance. S2: The system receives the user's natural language creation instructions in the dialogue input area. The loop engine module starts the ReAct loop, and the SSE event module pushes the output through the streaming protocol. When the task involves multiple steps, a structured execution plan is automatically generated. S3: The context engineering module determines the user's idea graph through a hybrid intent classifier and allocates token budgets for the four context planes. S4: The concentric growth module sequentially executes the EXPAND operations of the seed ring, core ring, and setting ring to generate character entities, attributes, relationships, and style facts. After the setting ring is completed, a mandatory user review gating is triggered. The user injects creative intent through the creative intent sub-layer of the three-layer maintenance module. S5: The concentric growth module executes the outline ring EXPAND operation to add events and structural facts. After reaching the density threshold, the PROJECT operation is executed to output the story outline. S6: The concentric growth module executes the EXPAND operation to generate scene-level events and character state changes episode by episode in sequence. After reaching the density threshold, the PROJECT operation is executed to output the episode outline. S7: The concentric growth module executes the text loop PROJECT operation, the format-aware co-creation module loads the target format constraints and format knowledge, and generates the format native script text; the constraint verification module executes hard constraint verification, and triggers a multi-round self-repair module when the constraints are not met; after completion, the RECONCILE operation is executed, and the emergent facts are written into the ledger through the ledger storage module.