Building a Local Web Fiction Knowledge Base Using LLM APIs: A Practical Guide

    This article outlines a practical approach to building a local knowledge base for web fiction using large language model (LLM) APIs. It covers the trade-offs between local deployment and cloud APIs, system architecture, text preprocessing and chunking strategies, hybrid retrieval and context assembly, prompt design, cost management, and quality evaluation to assist authors in analyzing and revising long-form web fiction.

    1. Why Choose a Local Knowledge Base with API Integration?

    During the creation and study of web fiction, authors often handle large volumes of materials, including full-length manuscripts, character profiles, world-building documents, outlines, and revision records. Web-based conversational tools are typically limited by single-input length constraints and server load, making it difficult to analyze extensive materials comprehensively. By storing materials locally and invoking models via APIs as needed, users retain full control over their data and processes.

    This approach offers four main benefits:

    • Controlled requirements: Users can define the retrieval scope, prompt templates, and output formats for better targeting.
    • Data privacy: Original texts are stored locally; only necessary snippets are sent to the model, reducing the risk of data leakage.
    • Flexible methods: Analysis frameworks—such as character consistency checks, foreshadowing tracking, and pacing analysis—can be customized according to creative needs.
    • Sufficient context: API calls are billed by usage and usually allow larger text inputs per request compared to web interfaces, making them suitable for long-text analysis.

    Since API calls incur costs and long texts increase expenses, it is essential to control the input size during the design phase.

    2. Trade-offs Between Local Deployment and API Invocation

    Full-scale large language models require substantial VRAM and RAM, meaning standard personal computers can usually only run distilled or compressed small models. These smaller models often fall short in long-text comprehension, complex logical reasoning, and style emulation, limiting their effectiveness for web fiction analysis. For most individual users, a more pragmatic approach is to keep material management and retrieval logic local while offloading model inference to cloud APIs.

    The main differences between the two approaches are as follows:

    Dimension Local Deployment (Small Models) Cloud API Invocation
    Hardware Requirements High (requires significant VRAM) Low (runs on standard PCs)
    Model Capability Limited by compressed parameter size Generally stronger
    Processable Context Length Limited by local VRAM Generally longer
    Cost Structure One-time hardware investment Pay-per-call billing
    Data Destination Remains entirely on the local machine Only required snippets sent

    Cloud services may experience slower response times, queuing, or failures during peak traffic. Programs should implement reasonable timeout limits and retry counts, and provide user interface prompts to indicate waiting, preventing users from misinterpreting delays as application failures.

    3. Overall System Architecture

    The knowledge base system can be divided into five layers, each with a single responsibility, facilitating isolated debugging and replacement.

    1. Data Layer: Collects manuscripts, profiles, outlines, and other files. Common formats include plain text, Markdown, and document files.
    2. Preprocessing Layer: Standardizes encoding, removes formatting tags and irrelevant content, and splits text by chapters.
    3. Indexing Layer: Generates keyword and vector indices for each text chunk and writes them to local storage.
    4. Retrieval Layer: Recalls relevant snippets based on user queries and controls the number of returned results.
    5. Generation Layer: Combines the query and recalled snippets into a prompt, invokes the model API, and formats the returned results.

    With this layered design, changing text splitting rules or replacing model services only requires modifying the corresponding layer without affecting the rest of the system.

    4. Data Preprocessing and Chunking Strategies

    Chunking quality directly determines retrieval effectiveness. Overly coarse chunking recalls irrelevant text, wasting context budget, while overly fine chunking fragments the plot, depriving the model of complete context.

    Recommended practices include:

    • Prioritize splitting by chapter, retaining chapter numbers and titles as metadata.
    • For lengthy chapters, further divide by paragraphs, keeping chunk lengths around a few hundred to a thousand characters.
    • Maintain a small text overlap between adjacent chunks to prevent critical sentences from being cut off.
    • Tag each chunk with characters, locations, timelines, etc., for subsequent conditional filtering.

    Below is illustrative chunking logic. The dependency for header recognition needs to be implemented according to the actual file format:

    1. def split_chapters(chapters, max_chars=1000, overlap=150):
    2. """Split a list of chapters into text chunks with metadata (illustrative)."""
    3. chunks = []
    4. for chapter in chapters:
    5. text = chapter["text"]
    6. start = 0
    7. while start < len(text):
    8. end = start + max_chars
    9. chunks.append({
    10. "content": text[start:end],
    11. "chapter_no": chapter["no"],
    12. "chapter_title": chapter["title"],
    13. })
    14. if end >= len(text):
    15. break
    16. start = end - overlap
    17. return chunks

    Deduplication should also be performed during preprocessing. Web fiction drafts often have multiple versions, and identical paragraphs may appear across different files. Without deduplication, retrieval results will be cluttered with redundant content, consuming context space.

    5. Retrieval and Context Assembly

    Relying on a single retrieval method is often insufficient. Proper nouns like character and location names are suited for exact matching, while conceptual questions like “Is this character’s motivation consistent?” rely on semantic similarity. Combining both methods generally yields better results than using either alone.

    The retrieval process can be executed in the following order:

    • Keyword Retrieval: Performs exact matching for proper nouns in the query to return chunks containing these words.
    • Semantic Retrieval: Computes vector similarity between the query and text chunks to return the most semantically relevant chunks.
    • Result Merging: Removes duplicate chunks and sorts them comprehensively by relevance.
    • Budget Trimming: Sets an input length limit; if exceeded, higher-relevance chunks are prioritized.

    Illustrative code is as follows:

    1. def build_context(query, index, budget_chars=8000, top_k=30):
    2. """Hybrid retrieval and context assembly based on character budget (illustrative)."""
    3. hits = hybrid_search(query, index, top_k=top_k)
    4. hits = sorted(hits, key=lambda h: h.score, reverse=True)
    5. context, used = [], 0
    6. for hit in hits:
    7. if used + len(hit.content) > budget_chars:
    8. break
    9. context.append(hit)
    10. used += len(hit.content)
    11. return context

    The budget limit should be determined based on the input restrictions and cost objectives of the service used. A limit too low may omit key plot points, while a limit too high increases costs and latency.

    6. API Invocation and Prompt Design

    When invoking the API, system instructions, user queries, and retrieved materials must be formatted into a standard message structure. The specific parameter names and formats depend on the official documentation of the service used. The illustrative code below outlines the process:

    1. def ask_model(api_key, model_name, system_prompt, question, context_chunks):
    2. """Assemble messages and request the model (illustrative, refer to service docs for specific API)."""
    3. material = "\n\n".join(
    4. f"[Chapter {c.chapter_no} {c.chapter_title}]\n{c.content}"
    5. for c in context_chunks
    6. )
    7. messages = [
    8. {"role": "system", "content": system_prompt},
    9. {"role": "user", "content": f"Materials:\n{material}\n\nQuestion: {question}"},
    10. ]
    11. return send_request(api_key, model_name, messages)

    There are three basic principles for prompt design:

    • Limit to provided context: Require the model to answer based solely on the provided materials. If information is missing, it should explicitly state “Not covered in the materials.” This is the primary method to reduce hallucinations.
    • Require citations: Answers should cite the referenced chapters for easy verification against the original text.
    • Fixed output structure: For instance, provide conclusions first, followed by evidence, and finally uncertainties, facilitating both programmatic and human reading.

    Typical application scenarios include:

    • Character consistency check: Comparing the actions, dialogue, appearance, and abilities of the same character across different chapters.
    • Foreshadowing resolution check: Listing clues that have been planted but not yet resolved, marking their locations.
    • Pacing analysis: Calculating conflict density, scene transition frequency, and information distribution across chapters.
    • Outline vs. manuscript comparison: Identifying paragraphs where the manuscript deviates from the outline, as well as outline events not yet implemented.

    7. Cost and Speed Control

    API costs are directly proportional to input character count, so the key to cost control is reducing ineffective input.

    • Retrieve before invoking: Send only relevant snippets instead of the entire book.
    • Hierarchical summarization: Pre-generate and store chapter summaries locally. For global questions, answer using summaries first, retrieving full text only when necessary.
    • Result caching: Directly return saved results for identical queries and materials.
    • Off-peak batch processing: Schedule large-scale analysis during low-traffic periods and set concurrency limits.
    • Usage monitoring: Log input character counts and costs for each call. Set daily budget limits and pause tasks when exceeded.

    8. Quality Evaluation and Precautions

    Model analysis conclusions require manual verification. Models may produce fluent statements that contradict the original text, especially on reasoning questions. Recommended practices include:

    • Sample and verify important conclusions against the original text to calculate error rates, determining the level of trust accordingly.
    • Programmatically verify chapter numbers cited by the model to ensure the corresponding text actually exists.
    • Maintain logs of questions, retrieval results, and model responses for backtracking and prompt refinement.

    Regarding material usage, only process original works or authorized texts, and avoid uploading unpublished manuscripts by others to any external service.

    9. Implementation Steps

    1. List clear analysis requirements (e.g., consistency checks, foreshadowing tracking, or pacing analysis) and define the required material scope for each.
    2. Organize the material directory, unify file formats and encodings, and establish standards for chapter numbering.
    3. Complete preprocessing, chunking, and indexing. Check if chunking results fragment the plot.
    4. Implement retrieval and context assembly, setting an initial character budget.
    5. Conduct a trial run with a small number of chapters. Manually verify if output conclusions align with the original text.
    6. Based on trial results, adjust prompts, retrieval weights, and budget limits, then gradually expand the material scope.

    By following these steps to build a local knowledge base, models can continuously assist in analyzing and revising long-form web fiction while controlling costs and privacy risks.