Building a Local Knowledge Base for Web Fiction: A Practical Guide to LLM API Integration
This guide explains how to build a local knowledge base for long-form web fiction and connect it to cloud LLM APIs. It covers a four-layer architecture, corpus preprocessing, hybrid retrieval, prompt design, and cost and latency control, showing how to keep data local while outsourcing heavy reasoning.
1. Why Keep the Knowledge Base Local
When writing long-form web fiction or organizing source material, pasting an entire work into a web chat box usually runs into three obstacles. First, the context window cannot hold hundreds of thousands or even millions of characters. Second, during peak hours the service is busy, so requests are rejected or queued for a long time. Third, unpublished drafts carry a leak risk when uploaded to an online session you do not control.
A local knowledge base addresses all three. Data stays on your own machine, and you decide the indexing strategy, chunking granularity, and methodology. When you call an LLM API, the context allowance per request is typically much larger than a web chat entry point, so you can feed in several chapters or even a whole volume for holistic reasoning. You also avoid competing with everyone else for the same online session resources.
One caveat: running a full-parameter LLM locally demands extreme hardware. Consumer-grade GPUs can only run smaller distilled models, which perform noticeably worse on long-range logical reasoning and character-relationship mapping. For most users, the more practical route is to keep data and retrieval local and obtain reasoning capability through an API.
2. Overall Architecture: Four Layers
A usable local knowledge base can be split into four layers, decoupled through explicit data contracts so implementations can be swapped.
- Text layer: raw chapter files, setting collections, and character cards, all converted to plain text with chapter metadata preserved (volume number, chapter number, word count, timeline position).
- Index layer: chunked text and their vector representations, persisted as local index files.
- Retrieval layer: recall relevant chunks for a question, then rerank and remove redundancy.
- Reasoning layer: assemble recalled results and the question into a prompt, call a cloud LLM API, and return the conclusion.
A sample data structure:
chunk = {"id": "vol1_ch012_p3","text": "...excerpt from this chapter...","meta": {"volume": 1,"chapter": 12,"timeline": "Day 3","characters": ["protagonist", "supporting character A"]}}
Preserving metadata matters because after a retrieval hit you can trace context along the timeline, avoiding conclusions that contradict the surrounding text when the AI sees only an isolated fragment.
3. Corpus Preprocessing: The Step That Sets the Ceiling
Web fiction has three traits: uneven chapter lengths, a high proportion of dialogue, and many repeated formulaic phrases. Preprocessing should be designed around these.
- Structure detection: use chapter titles and separators as anchors. Split by chapter first, then split again by semantic paragraphs, so a complete fight scene is not cut in half.
- Chunk size and overlap: keep each chunk to a few hundred characters, and retain a proportion of overlap between adjacent chunks so key references do not fall on a boundary.
- Noise cleanup: remove ad blocks, author notes, and repeated separator symbols, but keep character appellations, since appellations are important clues for later relationship inference.
- Metadata completion: tag each chunk with characters, locations, and time. This step can start with rules plus a dictionary, which is cheap and stable.
4. Vectorization and Retrieval
Convert chunks into vectors stored in a local index. At query time, vectorize the question and take the chunks with the highest similarity. In practice, combine two recall methods: vector recall handles cases that are semantically close but use different wording, while keyword recall handles exact matches such as proper nouns, move names, and place names. Merge and deduplicate both result sets before passing them to the reasoning layer.
More recalled chunks is not better. Increasing the chunk count linearly raises token consumption and response time while introducing irrelevant information that distorts judgment. A safe starting point is to recall fewer chunks first; if the model’s answer says information is insufficient, automatically widen the recall scope and retry.
5. Prompt Design and Model Selection
Prompt strategies should differ for the two needs mentioned above.
For setting lookups and fact-checking, the model must stay restrained and faithful to the source. The prompt should force it to answer only from the given fragments and to cite chunk IDs:
You may answer only from the [SOURCES] provided below, and must not use information outside them.If the sources are insufficient, reply exactly "Insufficient sources".At the end of the answer, list the cited source IDs as a list.[SOURCES][1] ...[2] ...[QUESTION]...
For plot simulation, logic-hole checks, and subplot expansion, the model needs to reason divergently. Here you should allow hypotheses but require it to separate “source-based evidence” from “speculation,” so guesses are not presented as conclusions.
On model selection, reasoning-oriented models are better suited to complex causal analysis and long-structure mapping, while general chat models respond more stably and cost less for plain retrieval and summarization. In real use, let the two types share the work rather than relying on only one throughout.
6. Call Wrapping, Cost, and Latency Control
Cloud APIs bill by token, and long-document scenarios can easily generate considerable expense, so engineering constraints are necessary:
- Cache layer: hash the same question plus the same context; return directly on a cache hit to avoid paying twice.
- Batching: merge multiple small questions into one request to cut the fixed overhead of repeated calls.
- Context trimming: send only recalled chunks instead of whole chapters, and use a summary index to coarse-filter before fine retrieval.
- Timeout and retry: set a reasonable timeout and use exponential backoff to avoid long idle waits during peak hours.
- Fallback strategy: switch to a backup channel or a smaller-parameter model when the primary channel is unavailable, keeping the pipeline running.
- Usage monitoring: log input and output size and latency for each request, review weekly, and locate abnormal consumption.
If response speed is critical, evaluate the provider’s high-priority channel or paid tier; for offline batch processing, a free quota plus queue waiting is usually enough.
7. Typical Workflow Example
Take “check the whole book for timeline conflicts”:
- Pull all chunks containing time descriptions from the index layer by time tag.
- Sort by timeline and feed them to the reasoning layer in batches, requiring a structured event table from each batch.
- Aggregate the event tables and run one global comparison, letting the model flag contradictory entries.
- Trace adjacent chunks to recheck suspicious entries, then finalize manually after confirmation.
Throughout the process, data stays local and only necessary text fragments are sent to the API, balancing privacy and quality.
8. Common Pitfalls
- Blindly pursuing a local LLM: with insufficient hardware, small-parameter models perform poorly on long-text reasoning and slow progress instead.
- Stuffing the whole book in at once: even if the context allowance is enough, cost and noise spiral out of control; a retrieval-based approach is more economical.
- Ignoring metadata: without chapter and time tags, the model cannot locate context, and conclusion reliability drops sharply.
- Skipping verification: all outputs should be spot-checked manually, especially conclusions about character relationships and causal inference.
9. Summary
The strength of a local knowledge base lies not in storage itself but in control: control over corpus, chunking, retrieval, and cost. Keep data and indexes local, delegate heavy reasoning to a cloud API, and constrain spending with caching, batching, and fallback strategies. This yields a stable, reusable workflow for long-text writing and material analysis. If you use Baidu AI Cloud capabilities for model calls and storage, the same layered approach applies, with selection and replacement done by general capability category.
