Skip to Content
AlgorithmsAlgorithms
  • Article
  • Open Access

11 May 2026

26 Pages

FictionRAG: A Stateful Metacognitive Framework for High-Fidelity Long-Narrative Role-Playing

,
,
and
1
School of Computer and Communication Engineering, Northeastern University, Qinhuangdao 066004, China
2
Research Institute of Unmanned Systems, Beihang University, Beijing 100191, China
*
Author to whom correspondence should be addressed.
†
These authors contributed equally to this work.

Abstract

Maintaining high-fidelity character personas and tracking trusted narrative facts remain significant challenges for LLM-based role-playing systems, particularly in long-context scenarios. Traditional Retrieval-Augmented Generation (RAG) approaches, which typically rely on static, stateless retrieval, often struggle to capture evolving plot dynamics, leading to character hallucinations and logical inconsistencies over prolonged interactions. To address these limitations, we present FictionRAG, a novel stateful retrieval-augmented framework designed to enhance long-narrative role-playing. FictionRAG introduces a hierarchical memory architecture that decouples narrative information into three distinct lanes: factual events, persona traits, and worldview constraints. Furthermore, it employs a failure-driven metacognitive regulatory loop that dynamically identifies and corrects retrieval deficiencies—such as persona drift or conflicting world rules—before response generation. By treating role-playing as a dynamic state tracking problem rather than simple question answering, FictionRAG ensures that generated responses are strictly grounded in both the narrative timeline and the character’s psychological profile. Extensive experiments on a dataset comprising twenty classic novels demonstrate that FictionRAG significantly outperforms existing baselines in factual accuracy, persona stability, and worldview consistency. Beyond literary role-playing, these results suggest that stateful, evidence-constrained retrieval can serve as a general mechanism for long-form controllable generation tasks that require persistent state tracking and multi-dimensional consistency.

1. Introduction

The rapid proliferation of Large Language Models (LLMs) has revolutionized interactive storytelling, enabling users to engage in open-ended dialogues with virtual characters derived from complex literary works [1]. Unlike standard task-oriented assistants, character-centric agents must satisfy dual objectives: preserving the factual trajectory of the original narrative while maintaining a consistent and distinctive personality [2]. Users expect these agents to not only recall specific plot details from the source text but also to react emotionally and logically in ways that align with the character’s established identity [3]. However, merely scaling up model parameters or employing naive prompting strategies often fails to capture the nuanced evolution of a character over long-narrative arcs, frequently resulting in generic responses that lack specific persona flavor or contradict prior plot developments [4]. Consequently, achieving high-fidelity role-playing that is both factually traceable and stylistically consistent remains a formidable research challenge.
Existing solutions predominantly utilize Retrieval-Augmented Generation (RAG) to ground model outputs in external knowledge bases [5]. While effective for factoid question answering, standard stateless RAG pipelines exhibit critical deficiencies in narrative simulation. First, they treat each dialogue turn as an isolated query, ignoring the cumulative “narrative state” that shapes character motivations. This often leads to fragmented evidence retrieval, where the model accesses disconnected facts without understanding their causal relationship [6]. Second, static retrieval mechanisms lack a self-correction capability. When retrieved context is ambiguous or conflicting—common in complex novels—the model often defaults to hallucination rather than seeking clarification or verifying constraints [7]. This statelessness is particularly detrimental in role-playing, where a character’s response is often dictated more by their current psychological state and implicit worldview rules than by explicit textual matches [8].
To overcome these structural limitations, this paper introduces FictionRAG, a stateful retrieval-augmented framework that reimagines narrative role-playing as a closed-loop metacognitive control process. Unlike systems that perform a single-pass retrieval, FictionRAG explicitly models the “narrative state” by tracking dialogue progression, character emotions, and world constraints in real-time. We propose a tri-lane hierarchical memory architecture that organizes information into factual events, persona traits, and worldview rules. When the system detects potential generation failures—such as a deviation from the character’s tone or a violation of narrative logic—it triggers a metacognitive regulatory loop. This loop iteratively generates probe queries to gather targeted evidence, resolving ambiguities before synthesizing a response. This mechanism allows FictionRAG to maintain global consistency across long interaction horizons, ensuring that characters evolve naturally without losing their defining core traits [9]. It should be noted, however, that the proposed framework is intended primarily for high-fidelity long-narrative role-playing scenarios, where narrative consistency, character fidelity, and world-state coherence are prioritized over minimum response latency. In this work, we treat long-narrative role-playing as a representative stress test for stateful controllable generation, because it simultaneously requires factual grounding, persona preservation, temporal state tracking, and implicit world-rule consistency. Under the same formulation, the proposed framework can potentially benefit broader applications such as interactive storytelling, game NPCs, educational simulations, historical or fictional character agents, and long-form collaborative writing support.
The principal contributions of this work are as follows: (1) We propose FictionRAG, a stateful role-playing framework that formalizes narrative interaction as a dynamic control problem, regulating factual and persona consistency through explicit state tracking. (2) We design a tri-lane hierarchical memory architecture that systematically decouples factual, persona, and worldview information, enabling precise retrieval and mitigating cross-domain signal interference. (3) We develop a failure-driven metacognitive regulatory mechanism that automatically diagnoses reasoning gaps using predefined sufficiency signals and triggers iterative refinement, significantly reducing logical contradictions in complex plots. (4) We construct a comprehensive benchmark dataset based on twenty classic novels and demonstrate through extensive evaluation that FictionRAG achieves superior performance in maintaining narrative fidelity compared to state-of-the-art baselines. To substantiate these claims, we formulate three core Research Questions (RQs) that guide our empirical evaluation: (RQ1) Does stateful interaction with an explicit metacognitive loop improve factual grounding, persona stability, and worldview consistency compared to stateless paradigms? (RQ2) Does decoupling evidence into distinct factual, persona, and worldview lanes yield measurable gains over reduced memory configurations? (RQ3) What is the quality–efficiency trade-off of the metacognitive retrieve–evaluate–probe–update loop concerning complex narrative generation tasks?

2. Related Work

2.1. Role-Playing Dialogue Systems and Persona Consistency

Building dialogue systems capable of faithfully recreating fictional characters represents a significant challenge in natural language processing. Such systems must possess fluent conversational abilities while simultaneously satisfying world-fact consistency and character-style consistency [10,11]. Early research primarily relied on manually constructed rules or templates, which proved difficult to scale to complex, long narratives.
With the rise of large language models, automatic methods for constructing role-playing chatbots have achieved significant progress. For instance, Shao et al. [12] propose Character-LLM, enabling the model to imitate character tone and knowledge by fine-tuning on a character-specific corpus. ChatHaruhi, introduced by Li et al. [13], segments long narratives into structured scenes using key entity recognition and coreference resolution techniques to build retrieval corpora, from which persona profiles containing style and emotion are extracted. During response generation, the system injects the retrieved scene evidence and persona features into the prompt to guide the model in generating character-appropriate content. This dual-pathway architecture, combining a factual pathway and a persona pathway, has demonstrated effectiveness in improving factual accuracy and stylistic fidelity [12]. Additionally, Huang et al. [14] proposed Emotional RAG to enhance role-playing by retrieving memories based on emotional states, inspired by psychological theories.
However, when facing evidence integration and state evolution in multi-turn dialogues, existing methods rely primarily on one-time prompt fusion. This static processing approach struggles to cope with dynamically changing contexts in long-term interactions. As noted by Tu et al. [4] and Chen et al. [15], when the dialogue deviates from the initial setting or involves complex plot deductions, the model is prone to persona drift or logical discontinuity, making it difficult to maintain long-term character consistency.

2.2. Retrieval-Augmented Generation for Long Narratives

Retrieval-augmented generation techniques are widely applied to alleviate knowledge obsolescence and hallucination issues in large language models [16]. The standard retrieval-augmented generation pipeline generally includes two stages: retrieving passages relevant to user queries from an external corpus, and subsequently using the retrieved evidence to guide the model in generating a response [17].
When processing long-narrative texts such as novels, traditional retrieval-augmented generation methods face unique challenges. Research by Liu et al. [6] indicates that naive fixed-length text chunking methods often disrupt natural narrative boundaries, resulting in retrieved contexts that lack coherence or introduce irrelevant information. Long-form narrative benchmarks have likewise shown that maintaining global coherence and cross-span dependency tracking remains intrinsically difficult for current language understanding systems [18]. To address this issue, researchers have proposed retrieval methods based on scene-level segmentation and metadata constraints, which better preserve narrative integrity. Furthermore, by combining techniques such as query rewriting, reranking, and global evidence organization [19,20], retrieval systems have significantly improved retrieval precision, thereby more accurately capturing complex plots and long-range dependencies in long texts [21].
Although these improvements increase retrieval accuracy, traditional retrieval-augmented generation remains a stateless, single-step retrieval paradigm. In complex role-playing scenarios, a single retrieval often fails to comprehensively cover plot clues spanning multiple chapters and struggles to process fragmented evidence generated during multi-turn interactions. This limitation prevents the system from maintaining narrative coherence and factual accuracy in long-term conversations.

2.3. Stateful Retrieval and Metacognitive Closed Loops

To overcome the limitations of traditional stateless single-step retrieval, recent research has begun exploring iterative closed-loop mechanisms triggered by reasoning failures [22,23,24,25]. Under this mechanism, the system no longer assumes that a single retrieval can acquire all necessary information. When the system encounters an information bottleneck or failure signal during reasoning, it generates probe queries to repeatedly retrieve and extract new evidence from hierarchical knowledge sources. This new evidence is encoded into memory units, fusing them into a global memory pool until the system obtains a logically self-consistent context [26].
For example, Self-RAG, proposed by Asai et al. [27], introduces a self-reflection mechanism, enabling the model to evaluate whether retrieved passages are relevant and whether generated responses are supported. ComoRAG, by Wang et al. [28], constructs a three-layer knowledge source comprising factual, semantic, and episodic layers, utilizing a dynamic memory workspace to organize cross-turn evidence. These studies demonstrate the effectiveness of metacognitive regulatory closed loops driven by failure signals in handling complex reasoning tasks [29,30,31].
Building on this foundation, FictionRAG deeply extends this framework to address the specific requirements of role-playing tasks. We incorporate critical elements—including persona, emotion, relationships, and scene locations—into explicit state representations, designating persona drift and worldview conflicts as core failure signals. Recent advancements in agent systems also highlight the necessity of such fine-grained state tracking; for instance, evaluating and maintaining granular state control has proven critical for GUI agents’ success [32]. By leveraging these failure signals to guide system retrieval strategies and state regulation, FictionRAG maintains character consistency and narrative coherence more effectively in long-term dialogues [33].

3. Method

3.1. System Overview

FictionRAG operates as a two-stage stateful retrieval-augmented role-playing framework designed for long-term dialogues. As shown in Figure 1 and Figure 2, the framework separates offline memory construction from online stateful regulation, allowing high-latency knowledge organization and low-latency dialogue control to be optimized independently. Its core objective is to jointly optimize three dimensions that frequently constrain one another during the generation process: factual accuracy, persona stability, and worldview consistency.
Figure 1. Offline stage of FictionRAG. The system preprocesses the source narrative and constructs retrieval-ready tri-lane memory for factual events, persona traits, and worldview constraints, forming the structured knowledge foundation used during online interaction.
Figure 2. Online stage of FictionRAG. Given the current dialogue state, the controller performs lane-aware retrieval, evidence sufficiency diagnosis, and iterative closed-loop refinement before response synthesis and state update.
In the t-th dialogue turn, given user input u t and target character identity c, the system must generate a response y t . To achieve stateful control, the FictionRAG controller maintains a joint state S t , the historical knowledge boundary available in the current turn H t , and an evidence set E t = { E t F , E t P , E t W } partitioned by lanes, effectively decoupling the semantic spaces of narrative facts and character traits. F, P, and W represent the factual lane, persona lane, and worldview lane, respectively. The core state transition process of the system can be formalized as:
y t = G θ u t , H t − 1 , S t , E t ; c , S t + 1 = T S t , u t , y t , E t
Here, S t serves as a dynamic control interface responsible for tracking dialogue intentions, model uncertainty patterns, and the sufficiency of each evidence lane. This state variable S t is not merely a scalar metadata tag but a composite vector comprising dialogue progression indicators, emotional valence scores, and a confidence distribution over the retrieved knowledge domains. This design fundamentally transforms the system from a traditional retrieve-then-generate open-loop paradigm into a closed-loop regulatory paradigm capable of controller-driven self-correction. The system no longer assumes that a single retrieval acquires all necessary information; instead, it explicitly evaluates whether current evidence is sufficient using a learned discriminator. If evidence is insufficient, the controller automatically reallocates the next retrieval focus according to predefined diagnostic signals, including lane-wise sufficiency scores, missing-evidence labels, and confidence thresholds. Here, “automatically” means that no human intervention is required during inference; the decision is constrained by the designed scoring and budget-allocation rules rather than by open-ended autonomous goal formation. From a macroscopic architectural perspective, FictionRAG contains modules operating on two distinct time scales. The offline stage handles high-latency, compute-intensive indexing tasks, constructing a stable memory foundation by transforming raw text into structured and schema-aligned representations. The online stage executes low-latency, adaptive closed-loop regulation within the continuously changing dialogue context. This decoupled design balances system controllability and universality, as the offline components provide structured prior knowledge that remains invariant across sessions, while the online components handle uncertainties during the dialogue process and make dynamic decisions based on real-time feedback.

3.2. Offline Construction of Hierarchical Memory

Algorithm 1 summarizes the offline construction procedure.
The offline construction stage aims to transform raw long-narrative text into retrievable structured data, rendering it both semantically independent and flexibly composable. Rather than serving merely as a preprocessing dependency, this stage functions as an indexing and memory-organization procedure for long narratives. Since the source text is typically available before interaction begins, constructing structured memory in advance reduces the need to repeatedly parse the full narrative during online generation. The constructed memory base is represented as a composite manifold:
X = { X F , X P , X W }
Here, X F stores traceable objective narrative facts. These facts are extracted using event extraction algorithms that identify subject–verb–object triplets and temporal markers, ensuring that every stored unit corresponds to a concrete occurrence within the narrative timeline. Specifically, we employ a dependency parsing model to isolate event triggers and their arguments, filtering out non-essential descriptive clauses to distill the narrative to its causal skeleton. X P stores linguistic style and behavioral clues related to the character persona. This lane is constructed by analyzing character dialogue patterns, extracting lexical density features, syntactic complexity metrics, and recurring catchphrases. We utilize a contrastive learning objective during this phase to maximize the distance between different character embeddings, ensuring that persona memory retrieval remains distinct for each role. X W stores worldview constraints and relationship priors, formalized as a knowledge graph where nodes represent locations, organizations, or metaphysical rules, and edges represent the logical or spatial relationships between them.
This stage adheres to two key design principles. First, lane identifiability ensures that each lane is assigned a distinct semantic role, enabling targeted mitigation of different failure modes—such as hallucination or persona drift—during online retrieval. For example, the factual lane verifies specific events, resisting the model’s tendency to fabricate plot points; the persona lane aligns character expression styles, preventing the degradation of the character’s unique voice into a generic assistant tone; and the worldview lane maintains long-range logical consistency, flagging contradictions in magic systems or political hierarchies. Second, cross-lane alignment without lane collapse enforces the use of uniform metadata, such as temporal anchors and scene identifiers, for alignment across different lanes, while strictly preserving the proprietary semantic features of each lane to avoid mixing them into a single homogenized representation. This is achieved by appending a global scene vector to every unit across all three lanes, serving as a synchronization key during the retrieval fusion process. Consequently, this design allows the system to purposefully strengthen retrieval in other lanes when evidence in one lane is insufficient, without losing shared contextual information. Furthermore, to improve system robustness, the offline stage lowers structural noise through canonicalization processing. The system resolves coreferences, normalizes temporal expressions to a relative timeline relative to the narrative start, and standardizes entity names using a pre-computed alias dictionary. Although inaccurate scene boundaries may reduce retrieval precision, the framework does not rely exclusively on scene-level segmentation, as character-related memory, world-state evidence, and contextual retrieval provide additional pathways for recovering relevant information. Its purpose is not only to improve retrieval recall but also to maximize the utility of retrieval results for generation control. In other words, memory units are shaped into structured objects suitable for iterative regulation rather than merely isolated text fragments.
Algorithm 1 Offline Construction
  1:
Input: raw narrative corpus D
  2:
Output: retrieval-ready memory base X = { X F , X P , X W }
  3:
S ← CanonicalizeAndSegment ( D )
  4:
X F , X P , X W ← ∅
  5:
for each scene s in S do
  6:
X F ← X F ∪ ExtractFactualUnits ( s )
  7:
X P ← X P ∪ ExtractPersonaUnits ( s )
  8:
X W ← X W ∪ ExtractWorldUnits ( s )
  9:
end for
10:
M ← BuildMetadata ( S )
11:
( X F , X P , X W ) ← AlignLaneMetadata ( X F , X P , X W , M , preserve _ lane _ semantics = True )
12:
X ← BuildRetrievalIndex ( { X F , X P , X W } )
13:
return  X

3.3. Tri-Lane Retrieval and Adaptive Resource Allocation

During each online retrieval round, the system first decomposes the current probe query. Instead of using a general query to cover all targets, FictionRAG dismantles it into specific intentions across the three dimensions of facts, persona, and worldview, mapping them to their corresponding memory lanes. This decomposition is performed by a specialized query generation module fine-tuned to recognize the subtle differences between questions regarding “what happened” (fact), “how would X say this” (persona), and “is this allowed in this universe” (worldview). This design isolates constraints regarding event occurrence, character tone alignment, and worldview compliance during the initial retrieval phase, effectively minimizing cross-domain noise interference and preventing different constraint signals from diluting each other in a single mixed retrieval. Importantly, although evidence accumulates over dialogue turns, the system does not exhaustively scan the full stored evidence pool at each generation step; instead, it retrieves only the context-relevant subset required by the current state, so growth in stored evidence does not necessarily imply a proportional increase in online processing cost. The advantages of explicit task decoupling to prevent signal interference have also been corroborated in other complex agent frameworks, such as separating natural language translation from heuristic search to ensure reliable planning [34]. At the execution level, the system establishes independent candidate sets for each lane and performs intra-lane reranking. Different lanes emphasize distinct ranking criteria. The factual lane ranking function prioritizes entity overlap and temporal proximity to the current dialogue state. The persona lane emphasizes expression habit compatibility, measuring the similarity between the required sentiment of the query and stored dialogue samples. The worldview lane focuses on rules and scene relationship constraints, penalizing evidence stemming from logically distant or incompatible narrative arcs. Formally, given the query q ℓ ( i ) for lane ℓ and candidate evidence d in the i-th iteration, the reranking score is calculated as follows:
s ℓ ( d ) = λ sem · sim ( q ℓ ( i ) , d ) + λ lane · compat ℓ ( d , s i , p ( i ) ) + λ div · diversity ( d , R ℓ ( i − 1 ) ) , ℓ ∈ { F , P , W } .
Here sim ( · ) measures fundamental semantic relevance using dense vector similarity using a pre-trained sentence transformer. compat ℓ ( · ) acts as a specialized filter: for F, it is a temporal coherence score; for P, a stylistic match score; and for W, a logical entailment score. The diversity term penalizes redundancy with previously retrieved documents. λ sem , λ lane , and  λ div are hyperparameters that balance the weights of these signals, which can be dynamically adjusted based on the controller’s confidence. This joint scoring mechanism effectively reduces pseudo-relevant fragments that are semantically relevant but violate task constraints, ensuring that retrieved content aligns with the current narrative state. After filtering candidate evidence, the system executes cross-lane resource reallocation. Specifically, the system evaluates the evidence support strength of the factual lane. If the factual evidence is weak, meaning the maximum evidence score m F ( i ) falls below the threshold τ low , the system dynamically transfers a portion of the retrieval budget from the factual lane to the persona and worldview lanes. This heuristic is based on the observation that when factual details are obscure or nonexistent, the model should rely more heavily on strong characterization and strict adherence to world rules to maintain immersion, rather than hallucinating details. This adaptive allocation heuristic shares underlying principles with decoupled exploration and utilization strategies in reinforcement learning [35], where the system automatically shifts its computational focus toward alternative high-yield dimensions based on predefined diagnostic rules when the primary objective encounters a bottleneck. This mechanism aims to mitigate hallucination risks—where the model exhibits a confident tone but lacks content due to factual absences—by supplementing character expression clues and setting constraints. The resource transfer process is formalized as:
δ ( i ) = min B shift , B F ( i ) / 2 · 1 m F ( i ) < τ low
B F ( i + 1 ) = B F ( i ) − δ ( i ) B P ( i + 1 ) = B P ( i ) + δ ( i ) / 2 B W ( i + 1 ) = B W ( i ) + δ ( i ) − δ ( i ) / 2
Here, B ℓ ( i ) represents the retrieval budget for lane ℓ in the i-th round, defined as the maximum number of tokens allowed for evidence chunks in that lane. δ ( i ) is the transferred budget increment, and  B shift is the maximum allowable budget transfer limit per round. Following this adaptive allocation process, the system outputs a structured tri-lane evidence package R ( i ) = { R F ( i ) , R P ( i ) , R W ( i ) } and proceeds to the next sufficiency evaluation stage.

3.4. Metacognitive Regulatory Closed Loop

Algorithm 2 details the online inference controller and metacognitive regulation process.
Algorithm 2 Online Inference and Metacognitive Loop
  1:
Input: user utterance u t , dialog history H t − 1 , role c, memory base X , max iterations I max
  2:
Output: final response y t , final evidence set E t , loop trace T t
  3:
( s 1 , p ( 1 ) ) ← InitController ( u t , H t − 1 , c )
  4:
P F , P P , P W ← ∅
  5:
T t ← empty list
  6:
i ★ ← I max
  7:
for  i ← 1 to I max  do
  8:
( q F ( i ) , q P ( i ) , q W ( i ) ) ← DecomposeProbe ( p ( i ) , s i )
  9:
for each lane ℓ in { F , P , W }  do
10:
C ℓ ← Retrieve ( X ℓ , q ℓ ( i ) )
11:
C ℓ ← RankBy ( C ℓ , s ℓ ( d ) = λ sem · sim ( q ℓ ( i ) , d ) + λ lane · compat ℓ ( d , s i , p ( i ) ) )
12:
R ℓ ( i ) ← SelectTopK ( C ℓ , k ℓ ( s i ) )
13:
end for
14:
( P F , P P , P W ) ← MergeEvidence ( ( P F , P P , P W ) , ( R F ( i ) , R P ( i ) , R W ( i ) ) )
15:
miss i ← DiagnoseMissing ( ( P F , P P , P W ) , s i , constraints = { F , P , W } )
16:
T t ← T t ∪ [ ( i , p ( i ) , { R F ( i ) , R P ( i ) , R W ( i ) } , miss i ) ]
17:
if  Sufficient ( ( P F , P P , P W ) , s i )  then
18:
i ★ ← i
19:
break
20:
end if
21:
p ( i + 1 ) ← UpdateProbe ( p ( i ) , miss i , s i )
22:
s i + 1 ← TransitionState ( s i , u t , ( P F , P P , P W ) , miss i )
23:
end for
24:
E t ← BuildFinalEvidence ( P F , P P , P W , i ★ )
25:
y draft ← DraftSynthesis ( u t , H t − 1 , E t , c )
26:
y grounded ← SuppressUnsupportedClaims ( y draft , E t , priority = [ F , W , P ] )
27:
y t ← PersonaRefine ( y grounded , E t P , preserve _ claims = True )
28:
return  ( y t , E t , T t )
The core of the online controller is an iterative retrieve–evaluate–probe–update closed loop. In the i-th iteration, the system first merges newly retrieved evidence from each lane into a persistent evidence pool:
P ℓ ( i ) = SortDesc Unique P ℓ ( i − 1 ) ∪ R ℓ ( i )
This monotonically increasing update strategy ensures that information accumulates during iterations, preventing the system from erroneously discarding potentially useful historical evidence during early uncertain phases, thereby guaranteeing convergence toward a comprehensive evidence set. The deduplication function Unique operates on evidence IDs to prevent redundancy. Subsequently, the system conducts a joint sufficiency evaluation on the current evidence pool across all activated lanes. The evaluator is set to detect three types of information voids: factual ambiguity, where key entities or events are mentioned but not described; motivating uncertainty, where the character’s internal reason for an action is unclear; and world-rule conflicts, where a proposed action might violate established lore. The evaluator outputs a global binary sufficiency decision alongside detailed diagnostic signals indicating which dimensions lack evidence and the confidence levels of each lane. If the evaluation determines that the evidence is insufficient, the probe strategy generates new queries based on these diagnostic signals. For instance, if a factual ambiguity is detected regarding a specific location, the next probe will explicitly target the description and history of that location. Therefore, the entire closed loop operates as a directed information acquisition process driven by specific failure signals rather than a blind, resource-intensive, fixed-depth recursive retrieval. The stopping condition of the closed loop is jointly determined by meeting sufficiency or reaching the maximum iteration count:
I ★ = min i ∣ Sufficient P ( i ) , A = 1 or I max
This design allows computational overhead to scale adaptively according to query complexity. For simple dialogue turns, the system can terminate retrieval early, whereas for complex plot nodes involving multi-party interactions or deep lore references, the system predictably invests more retrieval resources. Additionally, this closed-loop mechanism possesses exceptional diagnostic traceability. Each iteration generates explicit records binding probe queries, evidence growth, and sufficiency evaluation results together. This supports post hoc analysis of system failure causes, greatly improving engineering debuggability. By inspecting the loop trace T t , developers can pinpoint exactly which query failed to retrieve relevant documents or where a sufficiency check yielded a false positive.

3.5. Response Synthesis with Evidence Constraints

Upon completing the metacognitive closed loop, the system enters the final response synthesis stage. To ensure that the generated response respects both facts and persona, we adopt a constraint synthesis strategy based on evidence priority. The system first conducts content decisions and then performs optional style refinement. During content decisions, we establish a strict priority hierarchy in which the factual lane supersedes the worldview lane, which in turn supersedes the persona lane. Consequently, when lower-level stylistic clues conflict with higher-level factual or setting constraints, the system prioritizes retaining higher-level evidence, treating factual correctness as non-negotiable for narrative integrity. We implement this via a logit-biasing mechanism during the decoding phase. Tokens that form propositions contradicting high-priority evidence are assigned negative bias scores, effectively pruning them from the generation beam. At the semantic control layer, the system suppresses unsupported statements and potential logical conflicts via an evidence binding mechanism acting as a verification filter. This mechanism cross-references every generated claim against the evidence pool E t . If a claim is not entailed by the retrieved evidence, it is flagged for removal or revision. The generation process is strictly confined within the propositional space supported by the current evidence pool, systematically filtering any claims inconsistent with retrieved facts or world constraints. At the same time, factual evidence, character consistency, and worldview constraints may occasionally compete with one another during synthesis. Future refinements may therefore benefit from adaptive evidence weighting and explicit factual verification when preserving literal details becomes especially critical.
At the stylistic control layer, we employ a two-stage synthesis strategy. The system first generates a preliminary response draft centered on evidence consistency. This draft is typically dry and fact-focused. Subsequently, it refines the draft stylistically under the strict condition of claim preservation. We employ a rewriting module conditioned on the character’s persona description and previous dialogue history. This module is instructed to rewrite the draft to match the target character’s voice, vocabulary, and sentence structures, while being constrained to preserve all named entities and causal relationships present in the draft. Since the refinement stage operates solely at the expression level, factual assertions and world constraints remain stable, effectively preventing the sacrifice of semantic consistency for character style—a common pitfall in end-to-end models. In summary, the metacognitive regulatory closed loop is closely coupled with the constrained synthesis module. The former expands evidence boundaries and ensures information sufficiency, while the latter safely translates confirmed evidence into natural language responses that conform to character settings. This clear division of labor allows FictionRAG to maintain exceptional traceability and stability when facing complex scenarios characterized by sparse evidence, high contextual noise, or partially conflicting narrative conditions.

4. Experiments and Results

To validate FictionRAG in novel role-playing tasks, we design a hierarchical evaluation protocol focused on character consistency and factual accuracy. We compare FictionRAG with established baselines and perform ablation studies to isolate the effects of tri-lane retrieval components. Results quantify each module’s role in reducing long-context hallucinations and improving narrative coherence, providing empirical support for stateful role-playing agents.

4.1. Dataset Construction and Preprocessing

We establish a rigorous data collection and cleaning pipeline to ensure evaluation generalizability and narrative depth. The selection of the dataset is critical for assessing the capability of a model to maintain long-term context. We select twenty classic medium-to-long novels from Project Gutenberg covering adventure, mystery, and realism genres to construct a dialogue corpus dataset featuring high stylistic diversity. These novels were chosen not merely for their length, but for their intricate plot structures and complex character relationship networks, which pose significant challenges to traditional stateless retrieval systems. A comprehensive list of these novels and their categorical distributions is provided in Appendix A.
To address the lost-in-the-middle phenomenon and context window limitations of existing large language models, we propose a coarse-to-fine cascading framework. This framework operates in three distinct stages. First, we employ regular expressions for physical segmentation and noise removal at the chapter level. This initial pass removes non-narrative elements such as publisher metadata, table of contents, and copyright notices, ensuring that the subsequent processing stages focus purely on the narrative content. Subsequently, considering the spatio-temporal discontinuities often found within single chapters, particularly in modern literary styles where flashbacks or simultaneous events occur without explicit delimiters, we introduce a large language model for deep semantic parsing. This model is prompted to identify narrative shifts that regular expressions cannot detect, decoupling chapters into semantically independent scene units. Finally, we perform fine-grained information extraction at the scene level. This strategy significantly improves the signal-to-noise ratio of character dialogue extraction while preserving long-range contextual dependencies. By retaining the metadata associated with each scene, such as the participating characters and the location, we ensure that the retrieved context maintains its semantic integrity even when accessed out of linear order.

4.2. Baseline Methods

To evaluate the effectiveness of FictionRAG in long-term role-playing tasks, we select three categories of baseline methods for comparison. Baseline construction follows comparability principles where, without altering evaluation samples or scoring pipelines, non-key variables are controlled as much as possible, ensuring performance differences arise primarily from the use of retrieval augmentation and stateful organization. All baselines are evaluated using identical task interfaces where, given a sample represented by the current query, the character identity, and the dialogue history, the model outputs a single in-character response. This output is used to calculate factual accuracy, persona stability, worldview consistency, and pairwise win rates.
The first baseline is the vanilla large language model. This baseline adopts a pure generation paradigm where the model generates responses relying solely on current inputs and dialogue history, without introducing external retrieval evidence or maintaining cross-turn structured memory. This baseline delineates the capability boundaries of maintaining narrative and persona consistency relying on parametric memory and limited context windows. It serves as a control to demonstrate the inherent limitations of large language models when tasked with recalling specific details from training data that may be sparse or compressed.
The second baseline is the stateless retrieval-augmented generation method. This baseline adopts standard two-stage procedures where the system executes a single external retrieval based on the current query per turn, concatenating retrieved evidence fragments into the generation context. This baseline attempts to improve factual traceability through external evidence but operates without state assumptions, lacking cross-turn shared memory pools and evidence sufficiency evaluations. Consequently, it often experiences evidence fragmentation and insufficient cross-turn dependency coverage during long-term dialogues. By comparing against this baseline, we specifically isolate the performance gains attributable to the stateful, metacognitive aspects of FictionRAG, distinguishing them from the general benefits of retrieval augmentation.
The third baseline is EmotionalRAG [14]. This baseline enhances standard retrieval-augmented generation by explicitly modeling the emotional state of the character. In addition to retrieving narrative content, it employs an emotion classifier to detect the sentiment of the current prompt and retrieves dialogue examples with similar emotional labels from the character’s history. These emotional exemplars are added to the context to guide the model’s tone and stylistic expression. This baseline allows us to evaluate whether explicitly targeting emotional consistency can compensate for the lack of structural state tracking.
All implementations operate in a Python 3.13 environment utilizing GPT-4o-mini as the primary language model backbone. Experimental setups guarantee identical generation backends, retrieval corpora, input information boundaries, and evaluation pipelines across comparable models, with fixed reranking weights and closed-loop depths for FictionRAG to prevent biased tuning.

4.3. Evaluation Protocol

To comprehensively evaluate model performance in long-term novel role-playing tasks, we design a scene-level evaluation protocol. We employ a hybrid scoring mechanism that combines LLM-based judgments with deterministic text analysis to evaluate the quality of role-playing dialogue across multiple dimensions. All metrics are normalized to the [ 0 , 100 ] interval. The selected literary genres are particularly suitable for this evaluation because they contain long-range dependencies, demanding character consistency requirements, and persistent world-state constraints, all of which are central to the target task of long-narrative role-playing and make this setting a challenging testbed for stateful controllable generation more broadly.

4.3.1. Facts (Canon Grounding)

The Facts metric measures the consistency between the generated response and the original narrative facts. The LLM evaluator scores three sub-dimensions on a 1–5 scale: evidence_fit, fact_consistency, and timeline_consistency. The raw LLM score S LLM facts is the mean of these sub-dimensions. Simultaneously, a deterministic proxy score d facts calculates entity overlap. The final Facts score is obtained via weighted mixing and an upper bound constraint:
Facts = min ( w LLM · S LLM facts + w det · d facts , Cap facts ) × f usage
where S LLM facts is the normalized LLM score, Cap facts is the upper bound based on evidence sufficiency, and f usage is the evidence usage calibration factor.

4.3.2. Persona (Character Realization)

The Persona metric evaluates the match between the generated response’s linguistic style and the target character. The LLM evaluates five sub-dimensions: linguistic_style, tone, vocabulary, emotional_expression, and motivation_alignment. The deterministic proxy score d persona is based on entity and keyword recall of style markers. The final calculation follows the same structure as Facts:
Persona = min ( w LLM · S LLM persona + w det · d persona , Cap persona ) × f usage

4.3.3. Worldview (World Logic)

The Worldview metric measures whether the response adheres to the world setting and internal logic of the work. The LLM evaluates rule_consistency and setting_relation_consistency. The deterministic proxy score d world is based on keyword overlap of worldview evidence.
Worldview = min ( w LLM · S LLM world + w det · d world , Cap world ) × f usage

4.3.4. Overall Quality

The overall quality indicator is calculated in four steps:
Step 1: Weighted Base Score
Base = w F · S facts + w P · S persona + w W · S world + w U · S useful
where S represents the normalized score (0–100) for each dimension.
Step 2: Hybrid Penalty The system detects issues in the response, categorized as critical ( n c ), major ( n m ), and minor ( n i ). The penalty uses a mixed addition and multiplication mechanism:
Penalty ≈ ( α c n c + α m n m + α i n i ) ︸ Add + Base × ( β c n c + β m n m + β i n i ) ︸ Mult
Step 3: Dual-Track Scoring Two parallel scores are calculated: Quality: Deducts only issue penalties ( D issue ) and generation mode penalties ( D mode ). Role-Strict: Additionally deducts character mismatch penalty ( D char ) and evidence lane missing penalty ( D lane ) from Quality.
D char = P mismatch ( if character mismatch )
D lane = P lane × N disabled
Q strict = min ( Base − TotalPenalty , StructureCap )
where StructureCap is determined by the number of active evidence lanes.
Step 4: Final Fusion
Overall = w strict · Q strict + w quality · Q quality
This design biases the final score towards character consistency while retaining consideration for generation quality.

4.3.5. Reference Alignment

Reference Alignment is a purely deterministic metric measuring the text overlap between the generated response and the ground truth dialogue. It is a weighted sum of keyword recall, entity recall, and Keyword Jaccard similarity:
RA = 100 × ( w kw · R kw + w ent · R ent + w jac · J kw )
This metric serves as an auxiliary reference.
Additionally, we employ structured comprehensive evaluation frameworks leveraging multiple rounds of evaluation by language models as judges, specifically using GPT-4o as an impartial evaluator. To ensure robustness, we adopt median aggregation to filter extreme outliers and stabilize metric measurements. Final sample scores incorporate deterministic evidence alignment scores alongside judge ratings, applying sufficiency caps and evidence utilization penalties to prevent confident hallucinations. This multi-faceted evaluation strategy ensures that our metrics reflect both the creative quality of the role-play and its rigorous adherence to the source material. Detail hyperparameters are listed in Appendix B.

4.4. Experimental Setup

This section details the core configurations and hyperparameter settings for the conducted experiments. To ensure the comparability and reproducibility of the results, all baseline models and the proposed method operate within a unified experimental environment.

4.4.1. Implementation Environment

The experimental framework is deployed on the Ubuntu 22.04 LTS operating system using Python 3.13. The system employs openai/text-embedding-3-small as the primary embedding model and utilizes FAISS to construct an efficient vector database. GPT-4o-mini serves as the uniform backbone model for all inference tasks. In the main experiments, we set I max = 4 .

4.4.2. Data Preprocessing and Memory Construction

During the text preprocessing phase, a sliding window truncation strategy is applied to construct document-level memory. The chunk size is set to 2000 characters with an overlap of 200 characters between adjacent blocks. This overlap is critical for preventing context fragmentation at chunk boundaries. For speaker identification, this study adopts a hybrid approach that integrates rule-based heuristics with large language model reasoning. The key hyperparameters for this module include a sampling temperature of 0.0 to ensure deterministic outputs, a maximum generation length of 256 tokens, and the activation of a strict candidate constraint mode. This ensures that every line of dialogue is accurately attributed to the correct character, which is foundational for building reliable persona profiles.

4.4.3. Tri-Retrieve Hyperparameters

The tripartite retrieval mechanism, covering facts, persona, and worldview, utilizes unified candidate pool management and an adaptive dynamic truncation strategy. The initial candidate pool size is set to 60, with a dynamic retrieval range between 3 and 20 documents. For the dynamic thresholding, factors such as the score offset and global threshold are carefully tuned to filter out irrelevant noise while retaining potentially useful weak signals. Diversity in retrieval results is optimized using the maximal marginal relevance algorithm with a penalty factor of 0.7. This high penalty factor was chosen to force the system to retrieve distinct pieces of evidence rather than redundant confirmations of the same fact. The initial token budgets for the three retrieval paths are explicitly allocated to prioritize factual grounding while reserving sufficient capacity for stylistic nuance. We allocate 1200 tokens for facts, and 700 tokens each for persona and worldview data, allowing for a dynamic budget transfer of up to 300 characters based on the sufficiency evaluation. The coefficients for the weighted scoring function across the three branches are assigned to reflect their distinct priorities: the factual module emphasizes entity matching, the persona module focuses on speaker and style features, and the worldview module prioritizes location and organizational constraints.

4.4.4. Generation Strategy and Metacognitive Loop

The primary generation stage utilizes a sampling temperature of 0.2, while the style alignment refinement stage uses a strictly lower temperature of 0.1. This differential setting allows for some creativity in the initial content drafting while enforcing strict adherence to retrieved stylistic constraints during the refinement phase. The maximum generation length for both stages is limited to 700 tokens. The metacognitive retrieval loop is configured with I max = 4 in the main experiments. As shown later in Section 4.9, this value provides the best quality–efficiency trade-off before diminishing returns become pronounced. The trajectory tracking parameter is set to 6, and the generation length for new probes is restricted to 220 tokens. The decision module employs greedy decoding with a temperature of 0.0 to ensure consistent logic in the self-evaluation process.

4.4.5. Evaluation Configuration

To assess the quality of individual responses, the system implements a three-layer scoring mechanism that averages results across three independent rounds. This process sets the temperature to 0.2 and retains the top-6 candidate results for analysis. Unless otherwise specified, all ablation studies and comparative experiments in this paper follow the aforementioned configurations.

4.5. Main Results

To validate FictionRAG effectiveness, we first evaluate its performance on role-playing constraint satisfaction and narrative coherence. Table 1 displays the comparative results between FictionRAG and baseline models across all evaluation dimensions. Experimental data indicates that FictionRAG significantly outperforms vanilla large language models and stateless retrieval-augmented generation baselines across all core metrics. The improvements are not merely incremental but represent a fundamental shift in the model’s ability to handle complex narrative states.
Table 1. Performance comparison of FictionRAG and baseline models across evaluation dimensions.
As Table 1 shows, fine-grained analysis reveals limitations in baseline models concerning long-range narratives. When dialogue contexts exceed immediate memory windows or require tracking complex emotional evolutions, vanilla models and stateless pipelines tend to generate details inconsistent with original settings. Specifically, the stateless interactions often result in “hallucination loops,” where the model invents plausible but incorrect details to fill the gaps left by fragmented retrieval. FictionRAG, however, dynamically adjusts generation strategies based on the latest narrative state via its stateful retrieval mechanism. By maintaining a persistent state across turns, FictionRAG can verify its generated content against previously retrieved evidence, effectively acting as a self-correction mechanism.
The most striking improvement is observed in the Worldview metric, where FictionRAG achieves a score of 67.7135 compared to 37.6828 for the stateless baseline. This substantial gap highlights the effectiveness of the dedicated worldview lane and the hierarchical knowledge retrieval architecture. While standard retrieval methods treats all text as practically equal, our approach explicitly separates immutable world rules from transient plot events. This separation allows the model to enforce constraints even when the immediate dialogue context attempts to drift away from them. Furthermore, the Persona score sees a marked increase, confirming that treating persona as a distinct state variable rather than just a stylistic prefix leads to more stable and authentic character interactions.

4.6. Document-Level Observations

In addition to the aggregate results, we examined representative outputs from novels with different narrative structures. In clue-centric mystery cases, the main failure of stateless retrieval is not always factual absence, but fragmented evidence use: the model may retrieve the correct clue while ignoring whether the character should reveal it. In socially constrained realist novels, especially those involving marriage, class, or reputation, baseline systems often produce generic psychological explanations that overlook the governing social norms. In long-range adventure plots, baseline systems tend to lose delayed causal relations, particularly when a character’s present response depends on events that occurred many chapters earlier. FictionRAG handles these cases more robustly because the factual lane anchors plot evidence, the persona lane constrains expression and motivation, and the worldview lane maintains social or setting-level rules.
These document-level observations complement the aggregate results in Table 1. They also help explain why the largest aggregate improvement appears in the Worldview dimension: many long-narrative role-playing errors are not simple factual omissions, but violations of implicit social, relational, or setting-level constraints.

4.7. Qualitative Analysis

4.7.1. Case Setup

To illustrate how the quantitative improvements translate into interaction behavior, we present a representative case from the mystery subset of the evaluation set. The case is selected because it requires the system to simultaneously track a previously mentioned plot clue, preserve the character’s current motivational state, and avoid revealing information that the character would plausibly withhold. The input consists of the user utterance u t , the target character c, and the dialogue history H t − 1 .

4.7.2. Baseline Failure Patterns

Due to the limitation of the context window, the vanilla model resorts to a generic refusal, stating, “I don’t remember specifically,” which breaks the immersion of a detective character known for their sharp memory. The stateless retrieval-augmented generation model retrieves a relevant paragraph containing the clue but fails to integrate the character’s current emotional state of suspicion. It outputs the fact directly, “The letter was hidden in the drawer,” which is factually correct but stylistically flat and contextually inappropriate given the character is currently trying to hide this information.
EmotionalRAG improves tonal alignment by retrieving emotionally similar examples, but it still lacks an explicit mechanism for checking whether factual disclosure conflicts with persona or worldview constraints. As a result, it may produce a more in-character refusal or hesitation while remaining insufficiently grounded in the specific clue trajectory of the current scene.

4.7.3. FictionRAG Loop Trace

In contrast, FictionRAG executes a multi-step verification. First, the factual lane retrieves the content of the letter. Simultaneously, the persona lane retrieves the context that the character is currently suspicious of the inquirer. The metacognitive loop detects a potential conflict between “stating the fact” and “role-playing a suspicious character.” Consequently, it generates a response that is both factually grounded and character-consistent: “I found nothing of interest,” while internally updating the state to record this meaningful omission.

4.7.4. Interpretation

This example shows that FictionRAG does not simply retrieve more text than the baselines. Instead, it changes how retrieved evidence is used. The factual lane provides traceable support for what the character knows, the persona lane constrains how the character is likely to speak or withhold information, and the worldview lane prevents responses that violate the current scene logic. The metacognitive diagnosis identifies conflicts among these dimensions before final generation, which explains why the system can produce responses that are both grounded and in character. Table 2 summarizes the corresponding loop trace for this qualitative case.
Table 2. Representative loop trace of FictionRAG in the qualitative case.

4.8. Ablation Study

To isolate the contribution of the tri-lane memory structure, we compare three configurations: factual lane only (F), factual plus persona lanes ( F + P ), and the full factual-persona-worldview configuration ( F + P + W ). This design allows us to examine whether persona and worldview evidence provide complementary benefits beyond factual retrieval alone. Furthermore, we investigate the influence of the hyperparameter I max , which dictates the maximum allowable iterations within the metacognitive querying loop. The value of I max governs the maximum depth of the designed retrieve–evaluate–probe-update loop, thereby controlling how many rounds of diagnostic refinement the system can perform. By varying this threshold, we evaluate the inherent trade-off between reasoning depth and computational efficiency. While a restrictive I max may prematurely truncate the resolution of complex, multi-hop queries, an excessively high I max risks introducing diminishing returns, increased inference latency, and potential semantic drift. Consequently, this experiment seeks to identify the optimal iteration boundary that maximizes reasoning capability while preserving operational efficiency.
The results presented in Table 3 illustrate the distinct role of each component. The “Factual Lane Only (F)” configuration, which relies solely on fact-oriented retrieval, maintains a decent Facts score but suffers significantly in Worldview, dropping to a startlingly low 8.0034. This outcome is expected under our role-strict evaluation protocol. Worldview consistency requires explicit evidence about social norms, setting rules, relationships, and scene-level constraints. When the worldview lane is disabled, many responses lack the required support for these constraints and are therefore penalized heavily. Adding the persona lane in the “Factual + Persona Lanes ( F + P )” configuration restores much of the Persona, as the model can better capture stylistic patterns and speaking habits. However, the Worldview remains suboptimal at 38.1222. It is only with the full tri-lane architecture, where the worldview lane is also activated, that the Worldview jumps to 67.7135. This confirms our hypothesis that jointly modeling facts, persona, and world rules is essential for long-term narrative coherence. The slight dip in Facts in the full model compared to the “Factual + Persona Lanes ( F + P )” configuration is a trade-off: the full model occasionally sacrifices literal precision to maintain higher-level narrative and persona consistency, which is a desirable behavior in creative role-playing tasks.
Table 3. Ablation study results indicating the impact of removing hierarchical knowledge components on model performance.

4.9. Computational Efficiency

We examine efficiency from two complementary perspectives: a FictionRAG-specific iteration ablation and a cross-method runtime comparison. Table 4 and Figure 3 show that enlarging the metacognitive iteration budget I max steadily improves quality, but with predictable latency and token costs. When I max increases from 1 to 5, the Overall score rises from 44.3193 to 64.6852, while the average latency grows from 8.7438 s to 28.5209 s and the average total token usage increases from 1580.3983 to 5081.6479. This pattern is consistent with iterative retrieval-generation frameworks, where additional refinement rounds improve evidence coverage but also incur extra inference overhead [9,27,30].
Table 4. Ablation results under different maximum metacognitive iteration limits I max .
Figure 3. Trade-off curves across different metacognitive iteration budgets I max : increasing I max improves overall quality while simultaneously increasing average latency and token consumption.
From a deployment perspective, the critical observation is not merely that deeper control loops cost more, but that the gains begin to saturate after a moderate number of iterations. In our main setting, I max = 4 yields an Overall score of 62.6410 with 22.8232 s average latency and 4321.3583 tokens, whereas increasing to I max = 5 provides only a limited further gain. We therefore adopt I max = 4 as the default configuration because it offers the best practical balance between narrative quality and computational burden in our experiments.
Table 5 complements the iteration ablation by comparing end-to-end cost across different systems. FictionRAG is slower and more token-intensive than Stateless RAG and Emotional RAG because it performs controller-guided diagnosis, lane-specific retrieval, and evidence sufficiency checks before response synthesis. However, this added cost is structurally interpretable rather than incidental: the extra computation is directly tied to the mechanisms responsible for better factual grounding, persona stability, and worldview consistency. In other words, FictionRAG spends additional budget on explicit evidence verification instead of relying on a single-pass prompt fusion step.
Table 5. Efficiency comparison between FictionRAG and baseline methods.

5. Discussion

Synthesizing the experimental results above, FictionRAG achieves improvements across core dimensions including Facts, Persona, and Worldview. This phenomenon demonstrates that critical problems facing models in long-term role-playing tasks involve not only knowledge absence but also effectively organizing, selecting, and updating evidence during multi-turn dynamic interactions, especially when long-context utilization is imperfect and supporting evidence is scattered across turns or distant narrative spans [6,7].
To better interpret the source of these improvements, Figure 4 presents a conceptual comparison between FictionRAG and representative stateless baselines. Rather than relying on one-time prompt fusion, FictionRAG organizes evidence through explicit state maintenance, lane separation, and iterative metacognitive regulation, allowing the system to better accommodate evolving constraints over long interaction horizons.
Figure 4. Conceptual comparison between Vanilla LLM, Stateless RAG, and FictionRAG. By introducing stateful tri-lane retrieval and metacognitive regulation, FictionRAG supports more coherent, fact-traceable, and persona-consistent long-narrative generation.
As illustrated by this comparison, the central distinction of FictionRAG lies not merely in retrieving more evidence, but in regulating how different forms of evidence are accumulated, prioritized, and reused across turns. Unlike single-step retrieval paradigms adopted by traditional stateless methods rooted in standard RAG and dense-passage retrieval pipelines [5,17], FictionRAG introduces explicit state maintenance mechanisms and lane-separated evidence sets. Before each generation round, the system evaluates evidence sufficiency and cross-evidence consistency, adaptively adjusting retrieval focus and computational budget allocation based on these evaluations. This mechanism effectively reduces evidence fragmentation accumulation common in long narratives and lowers logical contradiction rates during multi-turn dialogues. More broadly, this design aligns with recent work arguing that long-horizon LLM agents benefit from explicit memory organization and controller-like reasoning loops rather than relying solely on larger context windows or one-shot prompting [8,22,25,28,29].
From the perspective of existing research, role-playing systems such as RoleLLM, ChatHaruhi, and Fic2Bot demonstrate the value of explicit role conditioning, scene grounding, and persona-oriented prompting for character simulation [2,13,36]. However, these pipelines still rely heavily on static or one-time fusion and therefore struggle against new constraints and potential conflicts constantly emerging as dialogues evolve. Meanwhile, retrieval methods with self-critique or corrective loops show that exposing reasoning failures can improve robustness in knowledge-intensive generation [27,30,33]. Building upon this line of work, FictionRAG incorporates role-playing-specific failure modes such as persona drift, weak factual support, and worldview violations as explicit diagnostic signals. The resulting tri-lane structure carries verifiable facts, reusable persona clues, and world constraints, allowing closed-loop retrieval to serve constraint satisfaction in controllable generation rather than generic answer expansion.
Ablation studies further reveal complementary relationships among the three evidence lanes. Retaining only the factual lane preserves local factual alignment but fails badly on worldview consistency because many role-playing constraints are not reducible to isolated events. Adding the persona lane substantially improves stylistic and behavioral consistency, yet important setting and relationship constraints remain under-specified. Only the full factual–persona–worldview configuration achieves balanced performance across all major dimensions, indicating that long-form character simulation depends on jointly modeling event traces, speaking style, and scene-level rule structure.
Regarding computational efficiency, the metacognitive regulatory closed loop incurs additional retrieval and evaluation overhead. Nevertheless, this cost remains controllable and interpretable. Sufficiency stopping conditions and budget reallocation mechanisms allow the system to adaptively assign retrieval depth, avoiding unnecessary delays on simple interactions. This trade-off is also consistent with recent self-reflective and corrective retrieval frameworks, where additional computation is intentionally spent on evidence verification rather than unconstrained generation [27,30]. This suggests a useful design principle for future role-playing systems: higher inference cost can be justified when it corresponds to traceable evidence gathering and explicit consistency control, rather than opaque prompt inflation.

Generalizability Beyond Literary Role-Playing

Although our experiments focus on classic novels, the proposed framework is not restricted to literary role-playing. FictionRAG formulates response generation as a stateful control problem over multiple evidence dimensions. This formulation can be transferred to other domains where generated text must remain consistent with a long-term context, including interactive games, pedagogical simulations, virtual companions, and collaborative writing systems. In these settings, the factual lane may correspond to task facts or environment states, the persona lane may correspond to user- or agent-specific behavioral profiles, and the worldview lane may encode domain rules, institutional constraints, or simulation policies.
Nevertheless, the present study adopts long narratives as the main testbed because they exhibit unusually dense combinations of plot causality, character evolution, social constraints, and long-range dependencies. Future work should evaluate whether the same tri-lane memory and metacognitive regulation mechanism generalizes to non-literary domains with different state structures and reliability requirements.
Despite these advancements, FictionRAG retains limitations. First, the metacognitive regulatory loop and dynamic retrieval strategy inevitably introduce additional computational overhead, making the framework more suitable for high-fidelity narrative applications than for strictly real-time deployment. Second, although offline memory construction is a practical design choice for long narratives, its quality still affects downstream retrieval performance, particularly when segmentation or canonicalization errors occur in difficult passages. Third, very long interactions may require more mature evidence compression and lifecycle management strategies to prevent stored information from becoming overly redundant. Finally, broader validation across different text types, multi-agent settings, and highly fragmented narrative structures remains an important direction for future work.

6. Ethical Considerations and Social Impact

FictionRAG is designed for character-based dialogue generation and long-form interactive storytelling, but the same mechanisms that improve consistency and immersion may also increase the persuasive power and apparent credibility of generated agents. This creates several ethical risks. First, highly consistent role-playing agents may encourage over-anthropomorphism or emotional over-attachment, especially in entertainment or companion settings. Second, stronger factual and stylistic grounding can make misleading or manipulative outputs appear more trustworthy if the underlying source material is biased, incomplete, or intentionally harmful. Third, literary character simulation raises questions about authorship, adaptation boundaries, and downstream misuse when deployed with copyrighted or culturally sensitive works.
Our framework partially mitigates these concerns by emphasizing evidence traceability, explicit sufficiency checks, and controllable retrieval pathways rather than unrestricted improvisation. Even so, these technical safeguards do not eliminate broader deployment risks. In practical applications, developers should combine systems such as FictionRAG with content moderation, source-governance policies, user disclosure that the interaction is machine-generated, and domain-specific restrictions for sensitive scenarios. We do not recommend deploying literary role-playing agents as substitutes for mental-health support, legal advice, or other high-stakes interactions without additional safeguards and specialist oversight.
The present study does not involve human subjects, clinical intervention, or personal sensitive data collection. The experiments are conducted on public literary texts and benchmark-style automatic evaluation pipelines. Nevertheless, future work should examine fairness and representation issues more directly, because character portrayals in canonical fiction often encode historical stereotypes, unequal social norms, or culturally specific assumptions that may be reproduced by a highly faithful agent.

7. Conclusions

This paper proposes a framework named FictionRAG targeting long-term novel role-playing tasks. This framework unifies factual grounding, persona representation, and world constraints into a diagnosable and adjustable control problem. By introducing tri-lane hierarchical memory, a metacognitive closed loop driven by failure signals, and an evidence-constrained response synthesis mechanism, FictionRAG dynamically updates narrative states during multi-turn interactions, thereby mitigating evidence fragmentation and persona drift issues caused by traditional stateless retrieval.
Experiments and ablation analyses suggest that FictionRAG is effective in the evaluated long-narrative role-playing settings, showing clear advantages across critical metrics such as consistency and immersion.
The core contributions of FictionRAG can be summarized as follows: (1) We propose a stateful retrieval-augmented generation framework for role-playing, unifying factual grounding, persona presentation, and world constraints into explicit state representations and a tri-lane evidence structure. (2) We construct a hierarchical memory foundation and cross-lane alignment mechanism, enabling evidence accumulation and composability across multi-turn interactions. (3) We design a metacognitive regulatory closed loop driven by failure signals, achieving targeted information acquisition and traceable diagnostic processes through sufficiency evaluations and budget adaptations. (4) We propose an evidence-constrained response synthesis strategy that preserves personalized character expressions while satisfying semantic consistency. (5) We establish a reproducible evaluation protocol and baseline models, providing comparison benchmarks and infrastructure for subsequent research in this field.
Overall, FictionRAG provides a systematic paradigm and evaluation baseline for extending retrieval-augmented generation technology from static knowledge enhancement to stateful controllable generation for complex role-playing. While the present evaluation focuses on long-narrative role-playing, the underlying formulation also offers a useful abstraction for broader long-form generation problems that require persistent state tracking and multi-dimensional consistency control. At the same time, the increased coherence and believability enabled by such systems make responsible deployment essential. Future work can therefore explore not only finer-grained persona modeling, more powerful cross-lane conflict governance mechanisms, and more efficient memory management strategies, but also stronger safeguards for transparency, source governance, and safe use in socially sensitive applications.

Author Contributions

Conceptualization, Y.D., Y.Z. and M.F.; methodology, Y.D., Y.Z. and J.Y.; software, Y.D. and Y.Z.; validation, Y.D., Y.Z., J.Y. and M.F.; formal analysis, Y.D., Y.Z. and J.Y.; investigation, Y.D., Y.Z. and J.Y.; resources, M.F.; data curation, Y.D., Y.Z. and J.Y.; writing—original draft preparation, Y.D. and Y.Z.; writing—review and editing, J.Y. and M.F.; visualization, Y.D. and Y.Z.; supervision, M.F.; project administration, M.F.; funding, M.F. All authors have read and agreed to the published version of the manuscript.

Funding

This research received no external funding.

Institutional Review Board Statement

Not applicable. This study does not involve human participants, animals, or clinical data.

Data Availability Statement

The dataset for this experiment is openly available at https://huggingface.co/datasets/mexdyf/fictionrag-dataset, accessed on 3 May 2026.

Conflicts of Interest

The authors declare no conflicts of interest.

Appendix A. Detailed Statistics of the Selected Novels for Dataset Construction

Table A1 lists the detailed statistics of the selected novels for dataset construction.
Table A1. Detailed statistics of the selected novels for dataset construction.

Appendix B. Hyperparameters for Evaluation Metrics

Table A2 lists the specific hyperparameter values used in our evaluation metrics.
Table A2. Hyperparameters and weights for evaluation metrics.

References

  1. Park, J.S.; O’Brien, J.C.; Cai, C.J.; Morris, M.R.; Liang, P.; Bernstein, M.S. Generative Agents: Interactive Simulacra of Human Behavior. In Proceedings of the 36th Annual ACM Symposium on User Interface Software and Technology (UIST), San Francisco, CA, USA, 29 October–1 November 2023; Association for Computing Machinery: New York, NY, USA, 2023; pp. 1–22. [Google Scholar] [CrossRef] [Scilit]
  2. Wang, N.; Peng, Z.Y.; Que, H.; Liu, J.; Zhou, W.; Wu, Y.; Guo, H.; Gan, R.; Ni, Z.; Yang, J.; et al. RoleLLM: Benchmarking, Eliciting, and Enhancing Role-Playing Abilities of Large Language Models. In Findings of the Association for Computational Linguistics: ACL 2024, Bangkok, Thailand, 11–16 August 2024; Association for Computational Linguistics: Stroudsburg, PA, USA, 2024; pp. 14743–14777. [Google Scholar] [CrossRef] [Scilit]
  3. Zhou, J.; Wang, Y.; Glantz, O.; Tsarkov, D.; Malheiros, W. CharacterGLM: Customizing Chinese Conversational AI Characters with Large Language Models. In Proceedings of the 32nd ACM International Conference on Information and Knowledge Management (CIKM), Birmingham, UK, 21–25 October 2023; Association for Computational Linguistics: Stroudsburg, PA, USA, 2023; pp. 4410–4414. [Google Scholar]
  4. Li, G.; Hammoud, H.A.A.K.; Itani, H.; Khizbullin, D.; Ghanem, B. CAMEL: Communicative Agents for “Mind” Exploration of Large Scale Language Model Society. Adv. Neural Inf. Process. Syst. 2023, 36, 51991–52008. [Google Scholar]
  5. Lewis, P.; Perez, E.; Piktus, A.; Petroni, F.; Karpukhin, V.; Goyal, N.; Küttler, H.; Lewis, M.; Yih, W.T.; Rocktäschel, T.; et al. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. Adv. Neural Inf. Process. Syst. 2020, 33, 9459–9474. [Google Scholar]
  6. Liu, N.F.; Lin, K.; Hewitt, J.; Paranjape, A.; Bevilacqua, M.; Petroni, F.; Liang, P. Lost in the Middle: How Language Models Use Long Contexts. Trans. Assoc. Comput. Linguist. 2024, 12, 157–173. [Google Scholar] [CrossRef] [Scilit]
  7. Yu, W.; Paranjape, A.; Hajishirzi, H.; Tsvetkov, Y. Chain-of-Note: Enhancing Robustness in Retrieval-Augmented Language Models. In Proceedings of the 2024 Conference on Empirical Methods in Natural Language Processing, Miami, FL, USA, 12–16 November 2024; Association for Computational Linguistics: Stroudsburg, PA, USA, 2024; pp. 14672–14685. [Google Scholar] [CrossRef] [Scilit]
  8. Zhong, W.; Guo, L.; Gao, Q.; Wang, Y. MemoryBank: Enhancing Large Language Models with Long-Term Memory. In Proceedings of the AAAI Conference on Artificial Intelligence, Vancouver, BC, Canada, 20–27 February 2024; AAAI Press: Washington, DC, USA, 2024; Volume 38. [Google Scholar] [CrossRef] [Scilit]
  9. Shao, Z.; Gong, Y.; Shen, Y.; Huang, M.; Duan, N.; Chen, W. Enhancing Retrieval-Augmented Large Language Models with Iterative Retrieval-Generation Synergy. In Proceedings of the International Conference on Learning Representations, Vienna, Austria, 7–11 May 2024. [Google Scholar]
  10. Wang, X.; Xiao, Y.; Huang, J.T.; Yuan, S.; Xu, R.; Guo, H.; Tu, Q.; Fei, Y.; Leng, Z.; Wang, W.; et al. InCharacter: Evaluating Personality Fidelity in Role-Playing Agents through Psychological Interviews. In Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), Bangkok, Thailand, 11–16 August 2024; Association for Computational Linguistics: Stroudsburg, PA, USA, 2024; pp. 1840–1873. [Google Scholar] [CrossRef] [Scilit]
  11. Jiang, G.; Xu, M.; Zhu, S.C.; Wen, Y. Evaluating and Inducing Personality in Pre-trained Language Models. Adv. Neural Inf. Process. Syst. 2023, 36, 58607–58625. [Google Scholar]
  12. Shao, Y.; Li, L.; Dai, W.; Qiu, X. Character-LLM: A Trainable Agent for Role-Playing. In Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing, Singapore, 6–10 December 2023; Association for Computational Linguistics: Stroudsburg, PA, USA, 2023; pp. 13628–13651. [Google Scholar]
  13. Li, C.; Ge, Z.; Zhang, W.; Wang, S. ChatHaruhi: Reviving Anime Character in Reality via Large Language Model. arXiv 2023, arXiv:2308.09597. [Google Scholar] [CrossRef] [Scilit]
  14. Huang, L.; Lan, H.; Sun, Z.; Shi, C.; Bai, T. Emotional RAG: Enhancing Role-Playing Agents through Emotional Retrieval. arXiv 2024, arXiv:2410.23041. [Google Scholar] [CrossRef] [Scilit]
  15. Chen, N.; He, Y.; Tang, G.; Sun, H.; Lei, Z.; Liu, Y. Large Language Models Meet Harry Potter: A Dataset for Aligning Dialogue Agents with Characters. In Findings of the Association for Computational Linguistics: EMNLP 2023, Singapore, 6–10 December 2023; Association for Computational Linguistics: Stroudsburg, PA, USA, 2023; pp. 8506–8520. [Google Scholar] [CrossRef] [Scilit]
  16. Zhang, Y.; Li, Y.; Cui, L.; Cai, D.; Liu, L.; Fu, T.; Hu, X. Siren’s Song in the AI Ocean: A Survey on Hallucination in Large Language Models. arXiv 2023, arXiv:2309.01219. [Google Scholar] [CrossRef] [Scilit]
  17. Karpukhin, V.; Oguz, B.; Min, S.; Lewis, P.; Wu, L.; Edunov, S.; Chen, D.; Yih, W.T. Dense Passage Retrieval for Open-Domain Question Answering. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing, Online, 16–20 November 2020; Association for Computational Linguistics: Stroudsburg, PA, USA, 2020; pp. 6769–6781. [Google Scholar] [CrossRef] [Scilit]
  18. Kočiský, T.; Schwarz, J.; Blunsom, P.; Dyer, C.; Hermann, K.M.; Melis, G.; Grefenstette, E. The NarrativeQA Reading Comprehension Challenge. Trans. Assoc. Comput. Linguist. 2018, 6, 317–328. [Google Scholar] [CrossRef] [Scilit]
  19. Sarthi, P.; Abdullah, S.; Tuli, A.; Khanna, S.; Goldie, A.; Manning, C.D. RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval. In Proceedings of the International Conference on Learning Representations, Vienna, Austria, 7–11 May 2024. [Google Scholar]
  20. Edge, D.; Trinh, H.; Cheng, N.; Bradley, J.; Chao, A.; Mody, A.; Truitt, S.; Metropolitansky, D.; Ness, R.O.; Larson, J. From Local to Global: A Graph RAG Approach to Query-Focused Summarization. arXiv 2024, arXiv:2404.16130. [Google Scholar]
  21. Zhang, H.; Liu, X.; Zhang, J. SummIt: Iterative Text Summarization via ChatGPT. In Findings of the Association for Computational Linguistics: EMNLP 2023, Singapore, 6–10 December 2023; Association for Computational Linguistics: Stroudsburg, PA, USA, 2023; pp. 10644–10657. [Google Scholar] [CrossRef] [Scilit]
  22. Packer, C.; Fang, V.; Patil, S.G.; Lin, K.; Wooders, S.; Gonzalez, J.E. MemGPT: Towards LLMs as Operating Systems. arXiv 2023, arXiv:2310.08560. [Google Scholar]
  23. Wei, J.; Wang, X.; Schuurmans, D.; Bosma, M.; Chi, E.; Le, Q.; Zhou, D. Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. Adv. Neural Inf. Process. Syst. 2022, 35, 24824–24837. [Google Scholar]
  24. Yao, S.; Zhao, J.; Yu, D.; Du, N.; Shafran, I.; Narasimhan, K.; Cao, Y. ReAct: Synergizing Reasoning and Acting in Language Models. In Proceedings of the International Conference on Learning Representations, Kigali, Rwanda, 1–5 May 2023. [Google Scholar]
  25. Sumers, T.; Yao, S.; Narasimhan, K.; Griffiths, T.L. Cognitive Architectures for Language Agents. arXiv 2024, arXiv:2309.02427. [Google Scholar] [CrossRef] [Scilit]
  26. Liu, L.; Yang, X.; Shen, Y.; Hu, B.; Zhang, Z.; Gu, J.; Zhang, G. Think-in-Memory: Recalling and Post-Thinking Enable LLMs with Long-Term Memory. arXiv 2023, arXiv:2311.08719. [Google Scholar]
  27. Asai, A.; Wu, Z.; Wang, Y.; Sil, A.; Hannan, H. Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection. In Proceedings of the International Conference on Learning Representations, Vienna, Austria, 7–11 May 2024. [Google Scholar]
  28. Wang, J.; Zhao, R.; Wei, W.; Wang, Y.; Yu, M.; Zhou, J.; Xu, J.; Xu, L. ComoRAG: A Cognitive-Inspired Memory-Organized RAG for Stateful Long Narrative Reasoning. arXiv 2025, arXiv:2508.10419. [Google Scholar] [CrossRef] [Scilit]
  29. Qian, H.; Liu, Z.; Zhang, P.; Mao, K.; Lian, D.; Dou, Z.; Huang, T. MemoRAG: Boosting Long Context Processing with Global Memory-Enhanced Retrieval Augmentation. In Proceedings of the Web Conference (WWW), Sydney, NSW, Australia, 28 April–2 May 2025. [Google Scholar] [CrossRef] [Scilit]
  30. Yan, S.Q.; Gu, J.C.; Zhu, Y.; Ling, Z.H. Corrective Retrieval Augmented Generation. In Proceedings of the ACM SIGKDD Conference on Knowledge Discovery and Data Mining, Barcelona, Spain, 25–29 August 2024; Association for Computing Machinery (ACM): New York, NY, USA, 2024; pp. 3676–3686. [Google Scholar]
  31. Jiang, Z.; Xu, F.F.; Gao, L.; Sun, Z.; Liu, Q.; Dwivedi-Yu, J.; Yang, Y.; Callan, J.; Neubig, G. Active Retrieval Augmented Generation. In Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing, Singapore, 6–10 December 2023; Association for Computational Linguistics: Stroudsburg, PA, USA, 2023; pp. 7969–7992. [Google Scholar] [CrossRef] [Scilit]
  32. Ji, F.; Yang, J.; Song, Z.; Wang, Y.; Cui, Z.; Li, Y.; Jiang, Q.; Fang, M.; Chen, X. FineState-Bench: A Comprehensive Benchmark for Fine-Grained State Control in GUI Agents. arXiv 2025, arXiv:2508.09241. [Google Scholar]
  33. Shinn, N.; Cassano, F.; Gopinath, A.; Narasimhan, K.; Yao, S. Reflexion: Language Agents with Verbal Reinforcement Learning. Adv. Neural Inf. Process. Syst. 2023, 36, 8634–8652. [Google Scholar]
  34. Tang, D.; Jiang, Q.; Yang, J.; Zhao, J.; Du, X.; Fang, M.; Zhang, X. SLTP: A Symbolic Travel-Planning Agent Framework with Decoupled Translation and Heuristic Tree Search. Electronics 2026, 15, 422. [Google Scholar] [CrossRef] [Scilit]
  35. Yang, J.; Wang, H.; Zhao, Q.; Shi, Z.; Song, Z.; Fang, M. Efficient Reinforcement Learning via Decoupling Exploration and Utilization. In Advanced Intelligent Computing Technology and Applications; Lecture Notes in Computer Science; International Conference on Intelligent Computing (ICIC 2024), Tianjin, China, 5–8 August 2024; Springer: Singapore, 2024; Volume 14863, pp. 396–406. [Google Scholar] [CrossRef] [Scilit]
  36. Kang, S.; Lee, C.; Jung, S.; Lee, M. Fic2Bot: A Scalable Framework for Persona-Driven Chatbot Generation from Fiction. Electronics 2025, 14, 3859. [Google Scholar] [CrossRef] [Scilit]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Article Metrics

Citations

Article Access Statistics

Multiple requests from the same IP address are counted as one view.