Building a Local Web Novel Knowledge Base with Large Language Model APIs
This article describes a setup for web novel writing in which the source materials stay on a local machine and a cloud large language model API handles inference. It explains why this split is practical for individual authors and small teams, outlines a four-layer architecture, and walks through document cleaning, chunking, indexing, prompt design, batch tasks, and human review. It also covers cost control, reliability, and security practices.
1. Problem Definition: Why Use a Local Knowledge Base with Cloud Inference
A web novel knowledge base typically includes world-building settings, character profiles, faction relationships, timelines, chapter text, outline drafts, reader feedback, and reference materials. Authors want language models to do more than answer questions. Typical tasks include chapter-by-chapter summaries, character relationship extraction, foreshadowing and payoff checks, power system consistency checks, pacing evaluation, logical contradiction detection, and comparison of multiple versions of a setting. These tasks place strict demands on context length, batch processing capacity, and output stability.
There are two common approaches: running a large model locally, or calling a cloud large model API. Local deployment keeps data on the machine and works offline. However, typical creative devices often cannot run a full-size large model. Smaller distilled or quantized models lower the hardware requirement, but they tend to fall short on complex setting comprehension, long-text reasoning, and factual consistency. For most individual authors and small teams, a more practical architecture keeps the source files, chunk indexes, task orchestration, and result archive locally, and calls a compliant large model API on demand for inference. This avoids pasting entire long manuscripts into a chat window at once. Local batch processing and caching also help control cost and latency.
An API call does not mean uploading all materials indiscriminately. Keep the full knowledge base locally. After retrieval, upload only the fragments, summaries, or structured setting cards relevant to the current task. Desensitize sensitive content first, store keys in environment variables or a key management service, and audit call logs. This layered approach underpins all the later steps.
2. Overall Architecture: Four Separated Layers
Splitting the system into four layers keeps long texts out of the model’s context window by default.
- Local file layer: Stores raw documents, cleaned text, chunking results, metadata, and index files.
- Retrieval and orchestration layer: Handles document parsing, chunking, keyword and vector retrieval, prompt assembly, batch queues, and writing results back.
- Model service layer: Connects to a compliant large model service through a general HTTP API. Each task uses either a general chat model or a reasoning-enhanced model.
- Output layer: Turns model results into structured reports, setting cards, issue lists, and revision suggestions.
The data flow runs in this order: import documents, clean and deduplicate them, chunk them by chapter or scene, build keyword and vector indexes, retrieve relevant fragments for each task, assemble prompts, call the API, parse the structured output, review it manually, and write it back to the knowledge base.
The key principle is retrieval augmentation rather than full-text dumping. A model with long-context capability should not receive every chapter at once. Chunked retrieval reduces token consumption and makes it easier to trace each conclusion to its source.
3. Environment Setup and Client Configuration
First, choose a compliant large model API provider. Register an account, confirm the billing method, set spending alerts, and create an API key. Enterprises can use the general-purpose large model API from Baidu AI Cloud after a compliance review. This article does not tie the workflow to any specific service, so refer to the official documentation for interface details.
Never write keys into code repositories or shared documents. Store them in environment variables, the system keychain, or a key management service, and rotate them regularly.
The client can be a general desktop application or a self-built script. It should support custom model service endpoints, file parsing, knowledge base indexing, and batch tasks. Use a recent stable version to avoid bugs in older parsers or session management.
Prepare two model configurations:
- A general-purpose model with low temperature and conservative output, used for material lookup, summarization, and format cleanup.
- A reasoning-enhanced model for logical deduction, contradiction detection, and complex setting analysis. It is usually slower and more expensive, so reserve it for key tasks.
4. Building the Knowledge Base: From Raw Material to Searchable Assets
Step 1: Classify materials. Create folders for world-building, characters, factions, timelines, chapter text, outlines, and reference materials. Name each file with the work title, volume and chapter, version, and date. Add metadata such as chapter number, character tags, timeline range, and version status. This metadata supports filtered retrieval later.
Step 2: Clean documents. Remove duplicate paragraphs, leftover advertisements, garbled text, and irrelevant annotations. Normalize encoding and punctuation, and keep chapter titles and scene separators. Convert setting material into structured tables or setting cards. For example, a character card can include identity, goals, ability limits, relationships, and the chapters in which the character appears.
Step 3: Chunk. Do not split text by a fixed character count. Split by chapter, scene, or setting entry first, and keep a small overlap of context between chunks. Attach the source, chapter number, and a short summary to each chunk so the model can cite its evidence.
Step 4: Index. Build both a keyword index and a vector index, and use hybrid recall during retrieval. For setting cards and character relationships, add tag filters.
Step 5: Design prompt templates. Each template should include the role, the task goal, the input material, the constraints, the output format, and instructions for marking uncertainty. Example pseudocode:
System prompt: You are a setting review assistant for web novels. Answer only from the provided material. If the material is insufficient, label the answer "insufficient evidence" and do not fabricate.User prompt: task={task_type}; material={retrieved_chunks}; question={question}; output=JSON with conclusion, evidence, risks, and revision suggestions.
The calling layer can be a general function with timeouts, retries, and caching:
def ask_model(client, model, messages):request = build_request(model, messages, temperature=0.2, timeout=120)return execute_with_retry(request, retries=3, backoff=exponential)def analyze_chapter(chapter_text, task):chunks = retrieve_relevant_chunks(chapter_text, task)prompt = build_prompt(task, chunks)return ask_model(client, select_model(task), prompt)
Step 6: Run batch tasks. Set up task queues for chapter summaries, character extraction, foreshadowing detection, logical contradiction checks, and pacing evaluation. Output results in a consistent JSON or Markdown table format.
Step 7: Review manually and write back. Spot-check model output and confirm that each conclusion traces to its evidence before writing it to the knowledge base. This prevents incorrect conclusions from polluting the index.
5. Model Selection and Prompting Strategy
Use a conservative model with low temperature for material lookup. Require the model to cite sources and mark uncertainty. For logical deduction, use a reasoning-enhanced model together with evidence snippets, and review the results manually.
Prompts should state several rules. The model must not invent settings that were not provided. When sources conflict, it should list the possible interpretations. It should also name the chapter where each piece of evidence appears.
For structured tasks, require fixed fields so that programs can parse the output. For open-ended analysis, require evidence before conclusions.
To compare models, build a small benchmark set and measure character consistency, timeline conflicts, and summary faithfulness. Record latency and cost alongside the quality results.
6. Cost, Reliability, and Security Governance
API usage is billed per token, so use layered summaries and caching. Chapter summaries, character cards, and retrieval results can be reused across tasks. Run batch jobs through queues with concurrency limits. Retry failed requests with exponential backoff, and handle rate limits, timeouts, and content errors separately. Process slow tasks asynchronously so they do not block interactive work. Set spending alerts, and keep audit logs that record the model, task, token usage, and latency for each call.
For security, upload only the material each task needs, desensitize sensitive information, rotate keys, and control access. For copyrighted material, keep records of the source and the license.
Several common issues come up in practice. A typical consumer computer is not suited to running a full large model locally. Small distilled models have limited effectiveness. Long documents should be retrieved first and then submitted in segments. Hallucinations are controlled through evidence citation, low temperature settings, and manual review.
With this architecture, authors can build a stable, traceable, and extensible local web novel knowledge base without expensive hardware.
