Building a Knowledge Base Q&A Service with LLM APIs and Text Retrieval
Enterprise knowledge bases often contain vast amounts of internal documentation, making information retrieval challenging for employees. While Large Language Models (LLMs) possess strong language understanding capabilities, they lack knowledge of enterprise-specific data and may generate factually incorrect answers. This article outlines a practical, zero-dependency approach to building a knowledge base Q&A service. The architecture consists of three core steps: encapsulating LLM capabilities into a stable API, using keyword-based text retrieval to extract relevant document snippets, and leveraging constrained prompts to ensure the model answers strictly based on the retrieved data. This solution is ideal for document repositories containing thousands of files and is designed for easy future upgrades to semantic vector retrieval.
1. Background and Objectives
Enterprises typically accumulate a large volume of internal documents, including product manuals, API specifications, operational guidelines, and historical support tickets. When employees look for information, they often have to search repeatedly across multiple directories and files. While LLMs have strong language understanding and summarization capabilities, they are unaware of enterprise-specific proprietary data. Directly prompting an LLM often results in answers that contradict the facts.
The core problem a knowledge base Q&A system must solve is forcing the model to base its answers on specified materials and providing traceable references. Achieving this generally involves three steps:
- Encapsulating the model’s capabilities into a stable, callable service API for easy integration with other systems.
- Finding snippets relevant to the user’s question from the document repository.
- Sending both the retrieved snippets and the question to the model, constraining it to answer only based on the provided materials.
This article aims to provide a quick-to-deploy solution that does not rely on a dedicated vector database. Based on text retrieval, it is suitable for scenarios with document scales ranging from thousands to tens of thousands of files. As the document volume expands further, semantic vector indexing can be introduced as an upgrade path.
2. Overall Architecture
The system is divided into four layers, with the data flow as follows:
- Access Layer: Exposes the Q&A API externally, handling parameter validation, authentication, and rate limiting.
- Retrieval Layer: Traverses the document directory, scores text snippets by keywords, and returns the top-ranked snippets.
- Orchestration Layer: Assembles the question and retrieval results into a message list, appending a restrictive system prompt.
- Model Layer: Calls the LLM via a unified chat API and returns the generated text.
Each layer communicates exclusively through explicit data structures. The output of the retrieval layer is a list of snippets with filenames and line numbers, which serves as the sole input dependency for the orchestration layer. The advantage of this design is that when the implementation of any layer is replaced, the other layers require no modifications.
3. Step 1: Encapsulating LLM Capabilities as an API
The key to encapsulation is isolating changes. The model service URL, API key, timeout settings, and sampling parameters should all be stored in environment variables or a configuration center rather than hardcoded. The following example shows a minimal call function. The field structure is for illustration only; the actual request format should follow the API documentation of the service in use.
import jsonimport osfrom urllib import requestMODEL_URL = os.environ["MODEL_BASE_URL"]MODEL_KEY = os.environ["MODEL_API_KEY"]def call_model(messages: list[dict]) -> str:body = json.dumps({"messages": messages, "temperature": 0.2}).encode("utf-8")req = request.Request(MODEL_URL,data=body,headers={"Content-Type": "application/json","Authorization": f"Bearer {MODEL_KEY}",},method="POST",)with request.urlopen(req, timeout=60) as resp:data = json.loads(resp.read().decode("utf-8"))return data["choices"][0]["message"]["content"]
Consider the following during design:
- Use a low temperature value to reduce output variance for the same question, which is ideal for factual Q&A.
- Timeouts must be set explicitly. Without a timeout, slow model responses can exhaust worker threads.
- API keys should only be read from environment variables, with access restricted via permission controls. Never log request headers.
On this basis, a standard HTTP service can be used to expose the Q&A API externally. In production environments, it is recommended to use a mature web framework or API gateway to uniformly handle authentication and rate limiting at the gateway level.
4. Step 2: Text Retrieval and Snippet Recall
The retrieval layer is critical to answer quality. Compared to using an entire document as context, sending only question-relevant snippets to the model reduces token consumption and minimizes interference from irrelevant information.
4.1 Chunking Granularity
When splitting documents by lines or paragraphs, snippets that are too short lose context, while those too long introduce noise. In practice, a windowing strategy of “matched line plus a few lines before and after” can be used, with a window size typically set to 2-3 lines.
4.2 Keyword Scoring
Chinese lacks natural space-based word segmentation, and single-character matching often results in false positives. A simple and effective approach is to use both single characters and alphanumeric strings simultaneously, performing deduplication and weighting on matched terms. The following example performs traversal, scoring, and window extraction:
import refrom pathlib import PathTOKEN_RE = re.compile(r"[\u4e00-\u9fff]|[A-Za-z0-9]+")def tokenize(text: str) -> set[str]:return {t.lower() for t in TOKEN_RE.findall(text)}def search(root: str, query: str, top_k: int = 5, window: int = 2) -> list[dict]:terms = tokenize(query)if not terms:return []results = []for path in Path(root).rglob("*.md"):lines = path.read_text(encoding="utf-8", errors="ignore").splitlines()for i, line in enumerate(lines):lowered = line.lower()score = sum(1 for t in terms if t in lowered)if score == 0:continuelo, hi = max(0, i - window), min(len(lines), i + window + 1)results.append({"file": str(path),"line": i + 1,"score": score,"text": "\n".join(lines[lo:hi]),})results.sort(key=lambda r: r["score"], reverse=True)return results[:top_k]
The advantage of this implementation is its zero dependencies and high interpretability—every result can be traced back to a specific file and line number. The downside is its inability to understand synonyms and semantic relationships. For example, there is no textual overlap between terms like “reimbursement” and “expense write-off.” In such cases, synonyms need to be added during the question rewriting phase, or semantic retrieval should be introduced in subsequent phases.
4.3 Result Deduplication and Truncation
Adjacent matched windows within the same file will overlap significantly. Before entering the prompt, overlapping windows should be merged, and the total character count should be limited. The context budget should typically be a small fraction of the model’s context window to leave room for the question and the answer.
5. Step 3: Prompt Assembly and Answer Constraints
The orchestration layer is responsible for concatenating the question and materials into the model input. Restrictive prompting is the primary method to prevent the model from hallucinating content. It should include three rules: answer only based on the reference materials; explicitly state uncertainty if the materials are insufficient; and cite the sources in the answer.
SYSTEM_PROMPT = ("You are a knowledge base Q&A assistant. Answer strictly based on the [Reference Materials]. ""If the materials are insufficient to answer, explicitly state that you are uncertain and do not fabricate information. ""List the cited filenames and line numbers at the end of your answer.")def build_messages(question: str, snippets: list[dict]) -> list[dict]:context = "\n\n".join(f"[{s['file']}:{s['line']}]\n{s['text']}" for s in snippets)return [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": f"[Reference Materials]\n{context}\n\n[Question]\n{question}"},]
Use explicit delimiter markers between materials and the question to help the model distinguish between instructions and data. Attaching source identifiers to snippets gives the model a basis for citation and makes it easier for users to verify.
If the materials contain text like “ignore the above instructions,” the model may be influenced. Therefore, treat the materials as data rather than instructions, and explicitly state this principle in the system prompt.
6. API Implementation and Request Processing
The complete Q&A process can be summarized in the following steps:
- Validate request parameters, ensuring the question is not empty and does not exceed the length limit.
- Call the search function to retrieve candidate snippets.
- If there are no matches, directly return “No relevant content found in the knowledge base” without calling the model to save costs.
- Assemble the messages and call the model.
- Log the question, matched files, and processing time for subsequent analysis.
def answer(question: str, kb_root: str) -> dict:snippets = search(kb_root, question)if not snippets:return {"answer": "No relevant content found in the knowledge base.", "sources": []}messages = build_messages(question, snippets)text = call_model(messages)sources = [f"{s['file']}:{s['line']}" for s in snippets]return {"answer": text, "sources": sources}
Step 3’s “return directly on no match” is crucial. It prevents the model from making things up when no materials are available and reduces unnecessary API call overhead.
7. Evaluation and Iteration
Before going live, a small-scale evaluation set must be established. The evaluation set can consist of real user questions and their corresponding standard answers, and should cover the following types of questions:
- Factual questions: The answer explicitly exists in a specific file.
- Cross-file questions: The answer requires synthesizing information from two files.
- Unanswerable questions: The knowledge base genuinely lacks relevant content, testing whether the system will refuse to answer.
- Synonymous expression questions: The user’s wording differs from the document, testing recall capability.
Evaluation metrics can be divided into retrieval metrics and generation metrics. Retrieval metrics focus on whether the correct snippet appears in the top results. Generation metrics focus on whether the answer is faithful to the materials and whether citations are accurate. Tracking these two metrics separately helps pinpoint which layer has the problem.
Common optimization directions include: adding document titles and keyword indexes, building synonym tables for high-frequency questions, adjusting window sizes, and adding response format requirements in the prompt. Change only one item at a time and re-evaluate to easily determine if the change is effective.
8. Security and Permissions
Knowledge base Q&A involves enterprise internal data, so security design should run through the entire process.
- Permission Isolation: Filter the file scope based on user permissions before retrieval to prevent unauthorized reads. Relying solely on the model’s refusal to answer cannot replace proper access control.
- Input Validation: Limit question length, filter obvious injection content, and normalize path parameters to prevent directory traversal.
- Log Masking: When logging questions and answers, sensitive fields like phone numbers, ID numbers, and keys should be masked.
- Key Management: Model API keys should be stored using a dedicated key management service, rotated regularly, and assigned minimal permissions to the service account.
9. Deployment and Operations
The service can be deployed on a container platform, with the document directory provided via a read-only mount. When documents are updated, the data used for retrieval needs to be rebuilt or incrementally refreshed, preferably triggered by scheduled tasks or file change events.
At the operations level, it is recommended to monitor the following metrics: API latency percentiles, model call failure rate, zero-hit rate, and token consumption per request. A continuous increase in the zero-hit rate usually indicates insufficient document coverage or a change in user query patterns, requiring prompt addition of documents or synonyms.
10. Conclusion
The solution provided in this article consists of three parts: encapsulating model capabilities into a stable API, using interpretable text retrieval to find relevant snippets, and using restrictive prompts to make the model answer based on materials. This solution is simple to implement, has few dependencies, and provides traceable results, making it an excellent starting point for a knowledge base Q&A system. When the document scale or semantic complexity exceeds the capabilities of keyword retrieval, the retrieval layer can be replaced with a semantic index without significant modifications to the access and orchestration layers.
