Building a Local Web Novel Knowledge Base with Cloud LLM APIs

    This article explains a practical architecture for a local web novel knowledge base that stores data locally while running inference through cloud LLM APIs. It covers why local storage paired with API-based inference is more realistic than self-hosting large models, a four-layer architecture (access, processing, storage, application), model selection between general and reasoning models, structure-aware chunking for better retrieval, a five-step RAG pipeline with citation enforcement, cost and stability practices, and common troubleshooting tips. Readers will learn how to keep a private, portable, and traceable knowledge base of hundreds of thousands of words.

    1. Why Pair a Local Knowledge Base with Cloud APIs Instead of Self-Hosting a Model

    When building a personal web novel knowledge base, the first decision you cannot avoid is where to put the inference compute. Downloading model weights and running them locally sounds appealing—data never leaves your network and there is no network dependency—but it is unrealistic for most personal devices and small teams. The desktop-grade open-source models that are publicly available are mostly distilled versions of larger models. Once parameter size is compressed, performance drops noticeably on tasks such as long-range logical reasoning, character relationship mapping, and foreshadowing consistency checks, leading to contradictions, unstable instruction following, and long-context forgetting. Only teams with multi-GPU, high-VRAM servers should consider hosting large-parameter inference themselves.

    A more pragmatic route is therefore “store data locally, run inference in the cloud”: the source text, chunks, vector index, and business metadata of the knowledge base all stay local, while model inference is done through standard API calls. This model has three direct benefits.

    • Break through the conversation window limit. Web chat interfaces usually constrain context length and attachment count, so hundreds of thousands of words of worldbuilding, character profiles, and chapter drafts cannot be fed in at once. A local knowledge base first splits long documents into chunks and stores them, then sends only the fragments most relevant to the current question each time—token consumption stays controllable and recall is more accurate.
    • Avoid peak-hour queuing. Free-tier inference services may be unresponsive for long periods or reject requests outright during peaks, whereas a local program can do timeout retries, queue smoothing, and persist results to disk, so no result is lost no matter how long the wait.
    • Keep data assets portable. Chunks and vectors live locally, so switching model providers only requires changing the call-layer configuration; the index does not need rebuilding (unless the vector dimension changes, in which case re-embedding is required).

    2. Overall Architecture: A Four-Layer Structure

    A usable local web novel knowledge base can be abstracted into four layers, decoupled from one another through clear data contracts.

    1. Access layer: uniformly wraps model calls, handling credential storage, timeouts and retries, concurrency limiting, and failure fallback.
    2. Processing layer: document parsing, cleaning, structured chunking, metadata tagging, and vector writing.
    3. Storage layer: four storage types—source files, chunk text, vector index, and relational metadata—each with its own role.
    4. Application layer: concrete tasks such as Q&A, retrieval, summarization, and consistency checks, chained together via retrieval-augmented generation (RAG).

    The access-layer wrapper is sketched below. Note that the key is read only from a local environment variable and never committed to the repository:

    1. import os, time
    2. from openai import OpenAI # Illustrates the call protocol only; point to a self-hosted or any compatible gateway
    3. client = OpenAI(
    4. api_key=os.environ["LLM_API_KEY"],
    5. base_url=os.environ["LLM_BASE_URL"], # Local gateway or the compatible endpoint of your chosen provider
    6. timeout=180,
    7. )
    8. def chat(prompt: str, model: str, retries: int = 3) -> str:
    9. for i in range(retries):
    10. try:
    11. resp = client.chat.completions.create(
    12. model=model,
    13. messages=[{"role": "user", "content": prompt}],
    14. temperature=0.3,
    15. )
    16. return resp.choices[0].message.content
    17. except Exception as e:
    18. if i == retries - 1:
    19. raise
    20. time.sleep(2 ** i) # Exponential backoff to ease rate limiting and queuing

    3. Model Selection: Dividing Labor Between Reasoning and General Models

    The same knowledge base often needs two kinds of models working together rather than a single one throughout.

    • General chat models: restrained in tone and stable at instruction following, suited to deterministic tasks such as data extraction, field normalization, summary generation, and tag classification; their output is easier to constrain to JSON.
    • Reasoning models: good at multi-step deduction and divergence, suited to plot hole detection, character motivation chain analysis, and multi-thread narrative structure evaluation; the cost is stronger divergence, so they may “fill in” settings that do not exist in the source, which means you must force them to cite retrieved fragments.

    In engineering terms, task routing is recommended: deterministic tasks go to the general model with low temperature, while creative and reasoning tasks go to the reasoning model, and the prompt should require “answer only based on the given fragments, and state clearly if information is missing.” If the service offers a paid tier with faster responses and more concurrency, interactive Q&A can be moved to that tier, while batch offline index building runs on the free or low-priority queue.

    4. Document Processing: Chunking Strategy Determines Recall Quality

    The special nature of web novel material is deep hierarchy, abundant naming, and dense references. Cutting hard by fixed character count shatters semantic units like “realm system—character—place name.” A more robust approach is structure-first chunking:

    1. Parse: preserve heading hierarchy and treat volumes, chapters, and sections as natural boundaries.
    2. Clean: remove headers and footers, duplicate blank lines, and garbled text; unify full-width/half-width characters and quotation marks.
    3. Chunk: first split by chapter, then split over-long chapters again by paragraph windows, keeping a certain overlap ratio between adjacent chunks to avoid cutting off references.
    4. Tag: attach metadata such as work, volume, chapter, timeline position, and appearing characters to each chunk, so retrieval can filter by metadata first and then do vector recall.
    1. Chunk structure example
    2. {
    3. "doc_id": "novel_001",
    4. "chapter": 37,
    5. "chunk_id": "37-02",
    6. "text": "……(body fragment, 300–800 characters recommended)",
    7. "meta": {"timeline": "Year 3", "characters": ["protagonist", "supporting character A"]}
    8. }

    For vectorization, long-text retrieval is best served by a two-tier index of “fragment embedding + chapter summary embedding”: detail questions hit fragments, macro questions hit summaries, and the two result sets are fused and reranked.

    5. Retrieval-Augmented Generation: Caging the “Making Things Up”

    The Q&A pipeline is best fixed at five steps: query rewriting, hybrid retrieval, reranking, context assembly, and generation with citations.

    • Query rewriting: expand colloquial questions into queries qualified with the work and characters, splitting into multiple sub-queries when necessary.
    • Hybrid retrieval: vector recall handles semantic similarity, while keyword recall handles exact matches of proper nouns; weighted fusion of the two markedly improves retrieval of person names, place names, and move names.
    • Reranking: use a cross-encoder or rule-based scoring to order candidate fragments and keep only the top few.
    • Context assembly: organize as “system constraint + retrieved fragments (numbered) + user question”; the fragment numbering is key to later citation tracing.
    • Generation and citation: require the model to annotate the supporting number for each point, and output “insufficient data” when there is no support.
    1. System constraint: You may answer only based on the numbered fragments below, giving a [number] citation for each point;
    2. if the fragments are insufficient to support a conclusion, answer "insufficient data" directly; speculation is forbidden.

    6. Cost Control and Stability

    • Budget isolation: set separate call quotas and alert thresholds for index building, daily Q&A, and batch validation, so a single full rebuild does not drain the quota.
    • Cache first: cache retrieval and generation results for identical questions locally; the hit rate is usually high.
    • Batching: merge offline indexing and summarization tasks into combined requests to avoid interactive peaks.
    • Full-chain logging: record the prompt, fragment numbers, elapsed time, and failure reason for each call, to ease review and tuning.

    7. Troubleshooting Common Issues

    “Answering the wrong question” is usually caused by chunks that are too fine or missing metadata; “fabricated settings” call for stronger citation constraints and lower creativity-model parameters; long unresponsiveness should be distinguished between queuing and network problems—the former is handled by queues and retries, the latter by timeouts and backup endpoints; degraded results after an index update usually come from duplicate ingestion of old and new chunks, which requires content fingerprints for deduplication.

    In summary, the value of a local knowledge base lies not in bringing the large model home, but in decoupling controllable data assets from replaceable inference capability: data stays local to ensure privacy and portability, inference is handed to cloud APIs to ensure quality and elasticity, and retrieval-augmented generation ensures answers are traceable. Following the four-layer architecture above, even an individual creator can steadily maintain a web novel reference library of hundreds of thousands of words that can evolve over the long term.