Building a Local Knowledge Base for Web Fiction with LLM APIs

    Learn how to build a locally managed knowledge base for serialized fiction using LLM APIs. This guide covers data organization, hybrid retrieval, text chunking, evidence-based consistency checks, privacy controls, cost management, and ongoing evaluation while keeping manuscripts under local control.

    Writers of serialized fiction often have plenty of ideas. What they lack is a reliable way to manage extensive story settings, chapter drafts, character relationships, worldbuilding notes, and reader feedback. Folders, spreadsheets, and memory may work initially, but as a series grows, continuity errors become harder to avoid: established facts conflict, plot threads disappear, and character voices drift.

    Browser-based chat tools introduce practical limits of their own. Context windows, service reliability under concurrent use, and the effort required to paste material repeatedly make them awkward for manuscripts containing hundreds of thousands or even millions of Chinese characters. Fully local model deployment, meanwhile, demands GPU memory, computing resources, and maintenance skills. Smaller models may run on ordinary hardware but still struggle with comprehension, consistent reasoning, and factual accuracy.

    For many independent writers, a more practical approach is to keep source material local and access model capabilities through an API. Manuscripts, story-analysis notes, setting documents, and revision histories remain on local disks or private storage. Only the necessary excerpts, after redaction, segmentation, and selection, are sent to an LLM inference API.

    This approach combines stronger cloud-based language understanding and reasoning with local control over source assets. Batch preprocessing also reduces repeated uploads, so each question does not require submitting the entire book.

    1. Define the Knowledge Base’s Scope and Goals

    Start by separating information into three categories:

    • Stable facts: Character names, power systems, geography, timelines, and important objects.
    • Changing state: Current injuries, relationship status, plot progress, and unresolved foreshadowing.
    • Preferences and methods: Authorial style, platform-specific pacing, chapter-hook templates, and the desired frequency of satisfying plot payoffs.

    Stable facts belong in structured storage. Changing state needs version numbers and timestamps. Preferences and writing methods should become reusable prompts rather than being mixed into manuscript content.

    Define success through three testable outcomes:

    1. Find relevant setting details quickly using a chapter number.
    2. Answer questions such as “Does this character know this secret?” with supporting citations.
    3. Check for continuity conflicts before drafting, including incorrect forms of address, inconsistent power levels, or the accidental return of dead characters and destroyed objects.

    Concrete goals make it easier to choose chunk sizes, design index fields, and build an evaluation set.

    2. Architecture: Local Assets, Indexing, and Inference

    A practical system has four layers.

    Local asset layer

    Store original manuscripts and setting files in directories organized by work, volume, chapter, and version. Keep read-only backups so that AI suggestions cannot directly overwrite the source text.

    Preprocessing layer

    Clean the text, split it into chapters and smaller units, remove duplicates, redact sensitive information, and extract metadata.

    Index layer

    Combine keyword and vector indexes.

    Keyword search supports exact matches for character names, magical artifacts, techniques, and other specialized terms. Vector search handles semantic similarity: “healing in a cold pool” and “recovering in an ice-aspected spring” may describe related events without sharing the same wording.

    Inference layer

    Assemble retrieved passages, task instructions, and style constraints into an API request. The model then produces analysis, inferences, or drafting suggestions.

    The overall workflow looks like this:

    1. Manuscripts/settings -> Cleaning and chunking -> Metadata tagging -> Keyword + vector indexes
    2. User question -> Candidate retrieval -> Reranking and compression -> Context assembly -> LLM API call
    3. Result -> Citation validation -> Conflict detection -> Suggestions area/manual approval before ingestion

    The following pseudocode illustrates the query path:

    1. def ask_novel_kb(question, work_id):
    2. candidates = hybrid_search(question, work_id, top_k=24)
    3. evidence = rerank_and_compress(candidates, max_tokens=6000)
    4. prompt = build_prompt(question, evidence, rules=load_style_rules(work_id))
    5. answer = llm_api.chat(prompt, temperature=0.2, max_output_tokens=1800)
    6. return validate_with_citations(answer, evidence)

    The important design choice is not a particular SDK. It is keeping retrieved evidence separate from generated conclusions in the system’s records.

    Each answer should be traceable to a chapter, paragraph ID, and ingestion version. Without that provenance, even a plausible interpretation is difficult to audit.

    3. Chunking: Preserve Meaning Without Wasting Context

    Fiction should not be split solely at fixed character counts. Chapters are natural boundaries, but individual chapters may still be too long for efficient retrieval.

    A better approach uses three levels:

    1. Split the work into chapters.
    2. Identify scene changes, viewpoint shifts, and time jumps within each chapter.
    3. For scenes that remain too long, group paragraphs into chunks of roughly 800–1,500 Chinese characters for Chinese source manuscripts.

    Each chunk should carry metadata such as:

    • Work ID
    • Volume and chapter numbers
    • Paragraph range
    • Characters present
    • Location
    • Timeline labels
    • Whether it contains combat
    • Whether it contains a romantic storyline
    • Whether it belongs to the final draft

    Avoid both extremes. Very small chunks lose context: a passage saying “he drew his sword” may not identify who “he” is. Oversized chunks consume API budget and dilute the evidence that matters.

    An alias table can map names and descriptions such as “the protagonist,” “the figure in black,” or “the senior apprentice” to stable entity IDs. During ingestion, a model can perform lightweight entity extraction, followed by human spot checks.

    This helps a question such as “When did Lin Heng learn the sect leader’s identity?” retrieve both passages that name Lin Heng explicitly and passages that refer to him indirectly.

    4. Model and Parameter Selection: Use Reasoning Selectively

    General-purpose LLM services may offer different model options emphasizing reasoning or generation.

    Reasoning-focused models can help with causal analysis, foreshadowing checks, timeline reconstruction, and problems involving multiple constraints. However, they may also fill gaps with plausible but unsupported explanations when evidence is incomplete. More restrained models suited to retrieval-based question answering can be a better fit for factual lookup, summarization, categorization, and format conversion.

    Route tasks accordingly:

    • Setting lookup: Use a low temperature and short output.
    • Logical analysis: Use a low-to-moderate temperature and require evidence supporting each inference.
    • Style-matched drafting: Allow more variation, while explicitly prohibiting new canonical facts.

    A useful prompt skeleton is:

    1. You are a continuity checker for serialized fiction.
    2. Use only the supplied evidence. Do not invent facts that are not present.
    3. Task: Assess the question and return:
    4. [Conclusion / Evidence / Uncertainties / Chapters Recommended for Review]
    5. If the evidence is insufficient, answer "Cannot confirm" and list the missing information.
    6. Style rules:
    7. Preserve the manuscript's established names and forms of address.
    8. Do not introduce new power levels, factions, or romantic storylines.

    For long manuscripts, retrieve first and read second. Do not submit the entire work indiscriminately just because an API supports a large context window. Larger inputs also increase cost, latency, and irrelevant context.

    Instead, retrieve around 20 candidates, rerank them, and retain six to ten highly relevant passages. Where useful, maintain rolling summaries of older chapters, storing each summary with pointers back to its source text.

    5. Privacy, Cost, and Reliability

    Concern about unpublished manuscripts leaving the writer’s control is a major reason to prefer local storage. Yet fully local deployment of a highly capable model can be demanding, while smaller models on limited hardware may be runnable without being useful enough.

    A hybrid architecture needs explicit rules about what may leave the local environment.

    Apply tiered redaction

    Unpublished plot developments, real-world personal information, and collaboration contracts should remain local by default.

    When external processing is necessary, replace real names, contact details, and payment information, and describe sensitive creative ideas at a more abstract level.

    Redact local logs as well. Store request hashes rather than complete sensitive source passages where possible, supporting cost tracking without retaining exposed manuscript content in logs.

    Use caching and batch processing

    Return cached results for identical questions.

    During chapter ingestion, batch together summary generation, entity extraction, potential-conflict identification, and embedding generation. This avoids repeating the same analysis during every question-answering request.

    Plan for API failures and delays

    Configure retries, timeouts, and fallback behavior. If the inference service is slow, return keyword search results and cached summaries first, then add deeper analysis asynchronously.

    Queues and rate limiting are more effective than repeatedly resending requests by hand, particularly when checking continuity across dozens of chapters during a busy publishing period.

    6. Evaluate Quality and Maintain the System

    A fiction knowledge base is an ongoing system, not a one-time setup.

    Maintain a small evaluation set with three types of questions:

    • Factual questions: “In which chapter does this artifact first appear?”
    • Relationship and knowledge questions: “Does Character B know Character A’s real identity?”
    • Conflict questions: “Can this technique still be used after Volume Three?”

    Run regression tests weekly or after each additional 50,000 Chinese characters of manuscript. Track retrieval hit rate, hallucination rate, and average response time.

    If a model upgrade or prompt change makes conflict detection worse, roll back the change rather than assuming newer capabilities are automatically better for the task.

    Ultimately, the measure of success is not how human the AI sounds. It is how much rework the system prevents:

    • Can it surface all relevant unresolved plot threads during a ten-minute prewriting review?
    • Can it identify chapters affected by a revision?
    • Can it turn useful reader comments into traceable changes to story canon?

    For independent writers, the value of a local knowledge base backed by LLM APIs is straightforward: let the system carry more of the memory burden while keeping creative decisions with the author. Controlled costs, access to longer-context analysis, more consistent output, and auditable continuity checks provide a sustainable foundation for AI-assisted writing.