Building a Local Knowledge Base for Web Fiction: A Practical Guide to LLM API Integration

    This article explains how to build a local knowledge base for Chinese web fiction writing by keeping the data layer on-device while calling models through remote APIs. It covers a four-layer architecture, how to choose between reasoning-oriented and general-purpose models, long-text chunking and hybrid retrieval, and practical controls for stability, cost, and data security. Readers will find reusable Python examples, prompt templates, and guidance on avoiding common retrieval and citation mistakes.

    1. Why a “Local Knowledge Base” Does Not Mean “Running the Model Locally”

    In Chinese web fiction writing, authors often accumulate millions of words of worldbuilding notes, character profiles, timelines, foreshadowing lists, and reference excerpts. Using an LLM to search, compare, and assist with continuation over this material is a classic knowledge base use case. Many beginners, however, assume that a “local knowledge base” requires running the model locally as well, and end up spending heavily on GPUs with disappointing results.

    One distinction matters here: the data plane of the knowledge base stays local, while the inference plane of the model can be remote. Local storage handles the raw documents, the chunked text, the vector index, and the retrieval logic; the model only needs to understand the question and generate an answer. As long as the retrieved context is passed over a standard API, the experience is close to full-corpus question answering.

    There are three reasons why self-hosting is not recommended for typical users:

    • Capability barrier: Truly large models with strong reasoning and long-context ability demand extreme amounts of VRAM, memory bandwidth, and interconnect capacity that consumer hardware cannot provide.
    • Gap in distilled versions: Common small distilled variants degrade noticeably on complex instruction following, long-form consistency, and multi-turn logic, and tend to produce off-topic answers when analyzing reference material.
    • Operational cost: Configuring inference frameworks, choosing quantization precision, troubleshooting VRAM overflow, and handling version upgrades all consume time that could otherwise go into writing.

    The conclusion is straightforward: moving compute to a cloud API while keeping data and workflow local is the most cost-effective path for ordinary users.

    2. Overall Architecture: A Four-Layer Breakdown

    A usable local knowledge base can be abstracted into four layers:

    1. Access layer: A unified model invocation wrapper that hides differences between providers and makes switching easy.
    2. Processing layer: Document parsing, cleaning, chunking, embedding, and index writing.
    3. Storage layer: Original files, text chunks, vector index, and metadata (source, chapter, timestamp).
    4. Application layer: Retrieval Q&A, setting conflict checks, character relationship mapping, and material aggregation.

    A sketch of the invocation wrapper looks like this. The key point is to extract the model name and API key into configuration so business code is not coupled to a specific provider:

    1. import os
    2. from openai import OpenAI # Standard client compatible with the OpenAI protocol
    3. client = OpenAI(
    4. api_key=os.environ["LLM_API_KEY"],
    5. base_url=os.environ["LLM_BASE_URL"], # Provided by your chosen provider
    6. )
    7. def ask(prompt: str, model: str, temperature: float = 0.3):
    8. resp = client.chat.completions.create(
    9. model=model,
    10. temperature=temperature,
    11. messages=[
    12. {"role": "system", "content": "You are a rigorous research assistant. Answer only based on the provided material."},
    13. {"role": "user", "content": prompt},
    14. ],
    15. )
    16. return resp.choices[0].message.content

    The benefit is that switching providers requires changing only two environment variables, while the retrieval and chunking logic is fully reused.

    3. Choosing Models: Reasoning-Oriented vs. General-Purpose

    The original practice noted two kinds of models: one strong at reasoning and divergence, effective but more prone to “improvising”; another more restrained, which feels better for plain lookup. This observation is easy to explain in engineering terms:

    • Reasoning-oriented models: Suited to setting extrapolation, foreshadowing payoff checks, plot logic hole detection, and comparing multiple options. The cost is that they need stronger constraint prompts, or they will add content that does not exist in the source.
    • General-purpose/instruction-tuned models: Suited to extractive Q&A, summarization, terminology unification, and format conversion. Output stays closer to the source text, and hallucination rates are relatively controllable.

    The practical recommendation is a “dual channel”: route retrieval questions to the general-purpose model and creative extrapolation to the reasoning model, and require cited sources in the prompt. A reusable constraint template:

    1. Answer only based on the material below; do not introduce outside information.
    2. If the material is insufficient, reply exactly: "Not covered by the material."
    3. Output format:
    4. Conclusion -> Evidence (source chunk ID) -> Uncertain items

    Also, if response latency matters, check whether the provider offers a paid acceleration tier; free quotas usually come with queuing and rate limits, and wait times during peak hours can reach minutes. The engineering answer is to make it asynchronous: put batch analysis jobs in a queue and show only progress in the frontend, so users never face a long unresponsive wait.

    4. Long-Text Handling: Chunking, Indexing, and Recall

    A web chat window has a limited context length, and repeatedly pasting long documents is costly. This is exactly where a local knowledge base adds value. The recommended flow:

    1. Parse: Convert documents to plain text, keeping chapter headings as hierarchy information.
    2. Chunk: Split on semantic boundaries, with 300–800 characters per chunk and 10%–15% overlap, avoiding cutting a sentence in half.
    3. Embed: Call the embedding endpoint to generate vectors and write them into a local vector store.
    4. Hybrid retrieval: Vector recall plus keyword recall, followed by reranking, which significantly reduces missed recall.
    5. Context budget: Cap the total injected fragments so the model has room to generate output.

    Chunking logic sketch:

    1. def split_text(text, size=500, overlap=80):
    2. chunks, start = [], 0
    3. while start < len(text):
    4. chunks.append(text[start:start + size])
    5. start += size - overlap
    6. return chunks

    Metadata is not optional. Recording “work title / volume and chapter / paragraph index / last updated” for every chunk is what lets conflict detection point to a specific source instead of returning a vague conclusion.

    5. Stability, Cost, and Risk Control

    • Retry and backoff: Use exponential backoff retries for timeouts and rate limits so a whole job does not fail.
    • Cache layer: Cache identical questions locally; repeat queries cost nothing.
    • Cost control: Run a small sample first, measure average token consumption, then decide on full ingestion; schedule batch jobs off-peak.
    • Fallback strategy: When the primary channel is unavailable, switch to a backup model or return the retrieved fragments and let the user judge.
    • Data security: Keep keys in environment variables or a secret management service, never committed to the code repository; redact sensitive unpublished manuscripts before ingestion.

    6. Common Pitfalls

    • Trying to stuff everything into the context while ignoring retrieval quality, which produces generic answers.
    • Chunks that are too large, so noise drowns out key information; or too small, so meaning breaks apart.
    • No citation labeling, which makes conclusions unverifiable and is especially risky in a writing workflow.
    • Treating the knowledge base as an “automatic writer” and skipping human final review.

    7. Conclusion

    The essence of a local knowledge base is using engineering to turn scattered material into structured assets that are searchable and verifiable. Replaceable models, elastic compute, and reusable workflows are what make a sustainable setup. For enterprise scenarios that need more complete managed capabilities, Baidu AI Cloud can be evaluated for its combination of general capabilities such as vector retrieval, object storage, logging, and monitoring alerts, to build a personal or team material hub as needed.