Building a Lightweight Knowledge Base Q&A System with an LLM API and Keyword Search

    This article presents a lightweight knowledge base question-answering architecture that combines a locally deployed large language model with keyword-based document retrieval. It explains how to expose model inference through an HTTP API, retrieve relevant document segments with grep-style matching, construct retrieval-augmented prompts, and apply engineering practices for concurrency, monitoring, security, and future upgrades to semantic search.

    1. Background and Objectives

    Enterprise knowledge management, customer support assistance, and document search often require systems that can answer natural-language questions using an organization’s internal documents. Although general-purpose large language models provide strong language understanding, they have two common limitations:

    1. They cannot access private enterprise knowledge and may generate confident but incorrect answers.
    2. Sensitive data may not be suitable for transmission to external services.

    A practical solution is to deploy the model privately, expose its inference capability through a service, and use retrieval to constrain the information available to the model.

    This article describes how to build a lightweight knowledge base Q&A system based on two core steps:

    1. Wrap a locally deployed large language model as a standard HTTP API and provide a unified integration endpoint.
    2. Before calling the model, use keyword matching—such as grep-style text search—to retrieve relevant segments from the knowledge base and inject them into the prompt as context. This provides a simplified form of retrieval-augmented generation (RAG).

    2. Overall Architecture

    The system consists of four modules:

    • Knowledge base layer: Stores source documents, which may be plain text, Markdown, or preprocessed document segments.
    • Retrieval layer: Extracts keywords from the user’s question, searches the knowledge base, and returns relevant segments.
    • Model service layer: Runs the large language model, receives a prompt containing the question and retrieved context, and generates an answer.
    • API gateway layer: Exposes a unified Q&A endpoint and handles parameter validation, authentication, rate limiting, and logging.

    The overall data flow is:

    User question → API gateway → Retrieved document segments → Prompt construction → Model API call → Answer

    This architecture is simple to implement and requires few dependencies. It does not require a vector database or an embedding model, making it suitable for rapid validation and small- to medium-sized knowledge bases.

    3. Exposing Model Inference Through an API

    Locally deployed models often interact through command-line tools or scripts. To simplify integration, their inference capabilities can be wrapped in a persistent HTTP service. For example, Python and a mainstream web framework can be used to implement a basic endpoint:

    1. from flask import Flask, request, jsonify
    2. import subprocess
    3. app = Flask(__name__)
    4. @app.route("/v1/generate", methods=["POST"])
    5. def generate():
    6. data = request.get_json()
    7. prompt = data.get("prompt", "")
    8. if not prompt:
    9. return jsonify({"error": "prompt is required"}), 400
    10. # Call the local inference script with timeout and exception handling
    11. try:
    12. result = subprocess.run(
    13. ["python", "infer.py", "--prompt", prompt],
    14. capture_output=True, text=True, timeout=120
    15. )
    16. return jsonify({"answer": result.stdout.strip()})
    17. except subprocess.TimeoutExpired:
    18. return jsonify({"error": "inference timeout"}), 504
    19. if __name__ == "__main__":
    20. app.run(host="0.0.0.0", port=8080)

    In a production implementation, several additional considerations are important:

    1. Concurrency control: Large model inference consumes significant computing resources. A process pool or task queue can be used to serialize requests or limit concurrency and prevent service overload.
    2. Streaming output: If the underlying inference engine supports streaming generation, the API layer can use Server-Sent Events (SSE) or chunked responses to improve the user experience.
    3. Parameter forwarding: Optional fields such as temperature and maximum generation length can be exposed so that upstream applications can adjust generation behavior.
    4. Health checks: A /health endpoint should be provided for integration with container orchestration probes and service monitoring.

    4. Implementing Knowledge Retrieval with Keywords

    The retrieval layer is responsible for quickly finding document segments related to a user’s question. A straightforward and efficient approach is to use text search tools, such as grep-style pattern matching.

    The basic workflow is:

    1. Preprocess documents: Split long documents into fixed-length segments, such as approximately 500 Chinese characters per segment. Store the source filename and segment number so that answers can be traced back to their origins.
    2. Extract keywords: Tokenize the user’s question, remove stop words, and retain the most important terms. Synonyms can also be added to improve recall.
    3. Search and rank segments: Match the keywords against the segment collection. Rank segments according to the number and positions of matched terms, then select the top results as candidate context.

    Example implementation:

    1. import subprocess, jieba
    2. def retrieve(query, top_k=3):
    3. keywords = [w for w in jieba.cut(query) if len(w) > 1]
    4. scored = {}
    5. for kw in keywords:
    6. out = subprocess.run(
    7. ["grep", "-rl", kw, "./kb_segments/"],
    8. capture_output=True, text=True
    9. )
    10. for f in out.stdout.splitlines():
    11. scored[f] = scored.get(f, 0) + 1
    12. ranked = sorted(scored.items(), key=lambda x: -x[1])[:top_k]
    13. return [open(f, encoding="utf-8").read() for f, _ in ranked]

    The main limitation of lexical matching is that it does not understand semantic similarity. Questions expressed with synonyms, paraphrases, or conversational language may achieve limited recall.

    As the knowledge base grows or accuracy requirements increase, the system can be upgraded to a hybrid retrieval strategy that combines keyword search with vector-based semantic retrieval. These approaches complement each other and can significantly improve overall retrieval performance.

    5. Q&A Orchestration and Prompt Design

    After retrieving relevant document segments, the next step is to organize them into an effective prompt. A recommended structure is:

    1. You are a knowledge base question-answering assistant. Answer the question
    2. using only the reference material below. If the material does not contain
    3. relevant information, clearly state that you cannot answer the question.
    4. [Reference Material]
    5. {segment 1}
    6. {segment 2}
    7. ...
    8. [User Question]
    9. {question}

    Instructing the model to answer only from the supplied materials and to explicitly acknowledge when the information is unavailable is an effective way to reduce hallucinations.

    The response should also include the source files of the retrieved segments whenever possible. This allows users to verify the answer and improves the overall trustworthiness of the system.

    6. Engineering Recommendations

    1. Knowledge base updates: When documents are added or modified, they should be segmented and indexed again. Scheduled jobs or message queues can be used to support incremental updates.
    2. Logging and monitoring: Record each question, the retrieved segments, and the generated answer. These records can be used to analyze bad cases and improve retrieval and prompt design.
    3. Authorization and security: Private knowledge Q&A systems must implement API authentication and data isolation to prevent unauthorized access.
    4. Cloud deployment: In a cloud environment, the services can be containerized and deployed on a container platform. Knowledge files can be stored in object storage, while logging and monitoring services can provide operational visibility and alerting. Load balancing can support horizontal scaling.

    7. Conclusion

    This article introduced a lightweight knowledge base Q&A solution based on an LLM API and keyword retrieval. A web service standardizes access to local model inference, text matching retrieves relevant segments from the document collection, and prompt constraints encourage the model to answer based on the retrieved materials.

    The approach has a low implementation cost and a straightforward processing flow, making it a practical starting point for validating enterprise RAG applications. As requirements evolve, the system can be extended with semantic vector retrieval, reranking, multi-turn conversation management, and other capabilities to form a more complete intelligent Q&A platform.