Developing Script Applications with LLMs: A Guide to Character Consistency
This article explores how to maintain character consistency when using Large Language Models (LLMs) to develop script and narrative applications. It analyzes the root causes of consistency issues, such as context window limitations and probabilistic generation, and proposes a five-step application-level solution framework. The guide covers structured character profiles, story bible maintenance, on-demand context injection, post-generation validation, and correction write-back loops, complete with engineering implementation examples and cost management strategies.
1. Background: LLMs as a Common Development Workflow
More and more developers are using Large Language Models (LLMs) to assist with application development. Models can generate UI code, outline business logic, write test cases, and assist in debugging and refactoring within terminal environments. For projects with numerous features and frequently changing requirements, this approach can significantly shorten the cycle from idea to prototype.
A single application typically involves two types of model calls: one during the development phase for code generation and troubleshooting, and another during the runtime phase to directly serve end-users, such as planning scripts based on user input, continuing plots, or generating dialogue. The goals, input scale, and billing methods of these two types of calls are different. Therefore, when analyzing costs, token usage should be tracked separately to avoid mixing them and being unable to identify which part incurs higher expenses.
Among all business scenarios, content-based applications have the highest requirement for “character consistency.” Once there are contradictions in a character’s appearance, personality, speech style, and relationships, readers will immediately notice, and the product experience will degrade significantly. This article focuses on this issue, discussing its causes, solution approaches, and specific implementations.
2. The Nature of Character Consistency Issues
2.1 Common Symptoms
Character consistency issues usually manifest in the following categories:
- Appearance Drift: Inconsistent descriptions of a character’s hair color, height, or clothing across different chapters.
- Personality Rupture: A previously composed character suddenly becoming impulsive without any narrative foreshadowing.
- Naming Confusion: Inconsistent forms of address between characters, such as changing from “Senior Brother” to “Brother” without explanation.
- Timeline Misalignment: Conflicts between a character’s age, experiences, or the sequence of events and previous text.
- Relationship Drift: Two originally hostile characters becoming inexplicably intimate later in the story.
These issues are not obvious in short texts but will appear frequently in long-form content.
2.2 Root Cause Analysis
There are three main reasons for the above issues.
First, the model’s context window is limited. When the script length exceeds the window capacity, early settings will be truncated or pushed out, and the model can only infer character information based on recent text.
Second, information utilization in long texts is uneven. Even if the settings are still within the window, the model’s reliance on this information decreases when the setting description is far from the current generation position.
Third, the generation process is essentially probabilistic sampling. The same piece of setting may yield different continuation results across multiple calls. Without external constraints, consistency cannot be guaranteed by the model itself.
Therefore, the core of the solution is not to hope the model “remembers,” but for the application to maintain character information at the system level and actively intervene before and after each generation.
3. Overall Solution Framework
The recommended solution in this article consists of five steps, executed sequentially from data to output.
- Structured Character Profiles: Break down character settings into fixed fields rather than a block of free text.
- Story Bible Maintenance: Centrally store global facts such as worldview, timeline, and character relationships.
- On-demand Context Injection: Only inject the characters and facts relevant to the current scene into the prompt during each generation.
- Post-generation Validation: Use rules or an auxiliary model to check if the output conflicts with the profiles.
- Correction and Write-back: Update validated content to the Story Bible for subsequent generation use.
The design points of each step are explained below.
3.1 Structured Character Profiles
The problem with free-text profiles is that the information is irretrievable and cannot be programmatically validated. Structured profiles fix key attributes, such as name, age, appearance, personality tags, speech style, relationship table, and experience timeline. Fields can be expanded as the project grows, but core fields should remain stable.
3.2 Story Bible Maintenance
The Story Bible records information that does not belong to a single character but affects the global setting, such as geography, historical background, factional relationships, and major events that have occurred. Its purpose is to provide a unified factual baseline for all characters. After each chapter is generated, new important facts should be appended to the Story Bible along with the chapter number for traceability.
3.3 On-demand Context Injection
All character profiles should not be stuffed into the prompt at once. A more reasonable approach is to first identify the characters appearing in the current scene, and then inject only the profiles and related facts of those characters. This controls the input length and reduces the interference of irrelevant information on the generation results.
3.4 Post-generation Validation
Validation is divided into two layers. The first layer is rule-based validation, suitable for checking content that can be precisely determined, such as age, name spelling, and fixed item names. The second layer is semantic validation, suitable for checking whether personality, relationships, and motives are reasonable. This can be handled by a separate model call, requiring it to return its conclusions in a fixed format.
3.5 Correction and Write-back
When validation fails, there are two processing methods: one is to submit the conflict description along with the original profile to the model and ask it to rewrite that specific part; the other is to flag it directly for human review. For high-value content, retaining a manual confirmation step is recommended. After passing validation, newly generated facts are written back to the Story Bible, forming a closed loop.
4. Engineering Implementation Example
The following example demonstrates the basic implementation of the above ideas. The code is only for illustrating the structure; in actual projects, it should be extended with error handling, persistence, and concurrency control based on business needs.
4.1 Data Structure for Character Profiles
from dataclasses import dataclass, field@dataclassclass CharacterProfile:name: strage: intappearance: strpersonality: list[str]speech_style: strrelations: dict[str, str] = field(default_factory=dict)timeline: list[str] = field(default_factory=list)
Using a dataclass instead of a plain dictionary provides field hints in editors and type-checking tools, reducing hidden issues caused by spelling errors.
4.2 Prompt Assembly
def build_character_prompt(profile: CharacterProfile) -> str:lines = [f"Name: {profile.name}",f"Age: {profile.age}",f"Appearance: {profile.appearance}",f"Personality: {', '.join(profile.personality)}",f"Speech Style: {profile.speech_style}",]for other, rel in profile.relations.items():lines.append(f"Relationship with {other}: {rel}")return "\n".join(lines)def select_context(scene_characters: list[str],profiles: dict[str, CharacterProfile],max_chars: int = 2000) -> str:parts, used = [], 0for name in scene_characters:block = build_character_prompt(profiles[name])if used + len(block) > max_chars:breakparts.append(block)used += len(block)return "\n\n".join(parts)
select_context concatenates profiles in the order of character appearance and sets a character limit. The limit should be set based on the context length of the model being used and task requirements; exceeding portions can prioritize keeping main characters.
4.3 Rule-based Validation Example
import redef check_age_consistency(text: str, profile: CharacterProfile) -> list[str]:issues = []for match in re.finditer(r"(\d{1,3}) years old", text):age = int(match.group(1))if age != profile.age:issues.append(f"Detected age {age}, which does not match the set age {profile.age}")return issues
Rule-based validation is low-cost and deterministic, making it suitable as the first line of defense before semantic validation. In actual projects, this can be extended in the same way to fields like forms of address, fixed items, and location names.
5. Collaboration Points for Development and Runtime
5.1 Tool Selection
The choice of development tools should be based on task characteristics, focusing on four aspects: task complexity, context-bearing capacity, ability to read and modify project files in the terminal, and whether the operation process is easy to audit. For refactoring tasks requiring modifications across multiple files, priority should be given to tools that understand the project structure and support step-by-step confirmation.
5.2 Tiered Cost Management
Runtime costs primarily come from the input and output length of each generation. Injecting character context using the method in the previous section directly controls the input scale. Auxiliary calls in the validation step also add overhead; semantic validation can be enabled only for key chapters or high-risk segments, while the rest uses only rule-based validation.
5.3 Logging and Traceability
It is recommended to log the character version used for each generation, the injected context summary, validation results, and correction history. When consistency issues arise, this allows quick identification of whether the cause is missing profile data, injection omission, or model output deviation.
6. Caveats and Boundaries
First, structured profiles cannot replace creative judgment. Character growth inherently includes personality changes; the system should allow profiles to be updated through explicit events rather than treating all changes as errors.
Second, rule-based validation has false positives. For example, the “years old” appearing in the text might refer to another character or a memory plot, so it needs to be judged in context.
Third, consistency mechanisms add latency and cost. Processing should be tiered based on the importance of the content to avoid applying the same intensity of checks to all content.
Fourth, when involving real people, brands, or sensitive content, compliance reviews should be added before and after generation, and one cannot rely solely on the character consistency mechanism.
7. Summary
Character consistency is a fundamental issue in long-form content generation, stemming from the model’s inability to stably store and retrieve long-term settings. Through structured character profiles, Story Bible maintenance, on-demand context injection, post-generation validation, and a write-back closed loop, consistency can be transformed from relying on the model’s self-awareness to being controllably guaranteed by the application. When implementing this, developers should first establish structured data, gradually introduce semantic validation, and keep development and runtime costs accounted for separately, achieving a balance between effectiveness and cost.
