Building a Knowledge Base Q&A Service with Text-Based Retrieval: A Practical Guide
Many teams already have a working inference program that generates text from prompts, but it can only be invoked from a local command line or a single script. This guide explains how to turn that capability into a minimal yet production-ready knowledge base Q&A service. It covers wrapping the inference backend as an authenticated HTTP API, adding a permission-aware retrieval layer based on line-by-line text matching (no vector models or dedicated index services required), and returning answers with verifiable source citations. The approach is low-cost, interpretable, and well suited to keyword-driven queries over a limited corpus.
1. Background and Goals
Many teams already have a working inference program that generates text from prompts, but it can only be invoked from a local command line or a single script. Business systems, internal portals, and multiple clients all need to access it over the network, and they also want it to answer questions based on the organization’s own documents.
This requirement can usually be broken down into two parts. First, wrap the inference capability as a stable, authenticated, observable API that different clients can call. Second, insert a knowledge retrieval layer between the user’s question and the model’s generation, so that answers are grounded in actual documents.
The goal of this article is to build a minimal viable knowledge base Q&A service. It does not rely on vector models or dedicated indexing services. Instead, the retrieval layer uses line-by-line text matching, behaving consistently with the command-line text search tools found in Unix-like systems. This approach is inexpensive to implement, produces interpretable results, and fits scenarios where queries are keyword-driven and the document set is limited in size.
1.1 When This Approach Fits
- Well-structured text materials such as internal policies, operation manuals, and API documentation.
- Queries whose wording closely matches the source text, such as error codes, configuration keys, and product terminology.
- Requirements for answer traceability, where users need to know exactly which file and which line an answer came from.
1.2 When It Does Not Fit
- Questions phrased very differently from the source text, which require semantic matching.
- Very large document sets where full scans introduce unacceptable latency. The exact threshold depends on machine performance, chunk size, and the number of query terms, and must be measured with your own data.
- Materials consisting of images, scanned documents, or tables, which require structured parsing first.
2. Overall Architecture
The service consists of four layers, each with a single responsibility, making them easy to replace and test.
| Layer | Responsibility | Implementation in This Article |
|---|---|---|
| Interface layer | Receives requests, authenticates, validates parameters, returns results | Standard HTTP service with JSON in and out |
| Orchestration layer | Chains retrieval and generation, controls context length | Plain stateless functions |
| Retrieval layer | Finds relevant passages from the knowledge base | Line-by-line regex matching and scoring after chunking |
| Inference layer | Generates answers from prompts | Client for an existing inference service |
The data flow for a single Q&A request is as follows.
- The client submits a question along with an access token.
- The interface layer validates the token first, then the request type, length, and field formats.
- The orchestration layer filters knowledge chunks by the user’s permissions, passes the question to the retrieval layer, and receives several relevant passages.
- The orchestration layer assembles the passages and the question into a prompt while controlling the total length.
- The inference layer generates an answer, and the orchestration layer attaches the citation sources before returning.
The benefit of this layering is that the retrieval layer can be swapped for an inverted index or vector search without changing the interface, and the inference layer can switch models without affecting business logic.
3. Wrapping the Inference Capability as an API
3.1 Interface Design
The interface exposes a single Q&A endpoint, avoiding passing the inference service’s internal parameters directly to clients. The request and response structures are as follows.
Request:
{"question": "How do I reset the service access token?"}
Response:
{"answer": "According to [1], resetting a token requires disabling the old token in the console first, then generating a new one.","sources": ["docs/auth/token.md"]}
Keep the following points in mind during design.
- Clients can only submit the question text. The retrieval scope, model parameters, and system prompt are all fixed on the server side to prevent tampering.
- The response includes source paths so users can verify answers. The source list only contains passages that actually entered the prompt.
- Errors are expressed with standard HTTP status codes: 401 for failed authentication, 415 for wrong content type, 400 for malformed requests or invalid fields, 413 for oversized request bodies, 404 for unknown paths, and 500 for internal exceptions.
3.2 Server Implementation
The example below uses only the standard library to show the basic structure of the interface layer. CHUNKS is the knowledge base loaded at startup; authenticate, visible_chunks, search, trim_hits, build_prompt, and call_llm are defined in later sections.
import jsonimport loggingfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerMAX_BODY_BYTES = 64 * 1024MAX_CONTEXT_CHARS = 6000NO_HIT_ANSWER = "No relevant content was found for this question. Please rephrase it or contact the documentation owner."logger = logging.getLogger("qa")class QAHandler(BaseHTTPRequestHandler):def do_POST(self):if self.path != "/v1/qa":self.send_error(404)returnprincipal = authenticate(self.headers.get("Authorization"))if principal is None:self.send_error(401)returncontent_type = self.headers.get("Content-Type", "").split(";")[0].strip()if content_type != "application/json":self.send_error(415)returntry:length = int(self.headers.get("Content-Length", "0"))except ValueError:self.send_error(400)returnif length <= 0:self.send_error(400)returnif length > MAX_BODY_BYTES:self.send_error(413)returntry:body = json.loads(self.rfile.read(length))except ValueError:self.send_error(400)returnif not isinstance(body, dict) or not isinstance(body.get("question"), str):self.send_error(400)returnquestion = body["question"].strip()if not question or len(question) > 500:self.send_error(400)returntry:visible = visible_chunks(CHUNKS, principal.groups)hits = trim_hits(search(visible, question), MAX_CONTEXT_CHARS)if hits:answer = call_llm(build_prompt(question, hits))else:answer = NO_HIT_ANSWERexcept Exception:# Log only the stack trace and user ID, never the raw question.logger.exception("Q&A processing failed, user=%s", principal.user_id)self.send_error(500)returnpayload = json.dumps({"answer": answer, "sources": [h.source for h in hits]},ensure_ascii=False,).encode("utf-8")self.send_response(200)self.send_header("Content-Type", "application/json; charset=utf-8")self.send_header("Content-Length", str(len(payload)))self.end_headers()self.wfile.write(payload)if __name__ == "__main__":logging.basicConfig(level=logging.INFO)server = ThreadingHTTPServer(("127.0.0.1", 8080), QAHandler)server.serve_forever()
The code authenticates before parsing the request body, so unauthenticated requests do not consume parsing resources. Retrieval and inference are wrapped in a try block so that any exception becomes a 500 response without interrupting the server thread. Logs record only the user ID and the stack trace; the raw question is never written to logs.
The example listens on the loopback address by default. When exposing the service externally, place it behind a reverse proxy that centrally handles TLS, rate limiting, and access logs.
3.3 Connecting to the Inference Service
The inference layer needs only one function that takes a list of messages and returns text. This way, the orchestration layer does not need to care about the underlying deployment form.
def call_llm(messages: list[dict]) -> str:"""Call the deployed inference service and return the generated text.Read the endpoint and credentials from environment variables;a timeout of 30 seconds or less is recommended."""raise NotImplementedError("Replace with your team's inference service client")
In a real implementation, pay attention to the following.
- Inject endpoints and credentials via environment variables or a secrets management service; never write them into code or logs.
- Set both connection and read timeouts so a single slow request cannot exhaust all threads.
- Apply limited exponential backoff for retryable errors, and fail immediately on parameter errors.
3.4 Authentication and Access Control
A knowledge base Q&A service often touches internal materials, so the API must require authentication. The example below uses Bearer tokens. The server stores only the SHA-256 digest of each token; the plaintext token is held by the client. At startup, TOKEN_TABLE is loaded from a secrets service, with digests as keys and user identities as values.
import hashlibfrom dataclasses import dataclass@dataclass(frozen=True)class Principal:user_id: strgroups: frozenset[str]# Keys are SHA-256 digests of tokens, loaded from a secrets service at startup.# No plaintext tokens appear in the code.TOKEN_TABLE: dict[str, Principal] = {}def authenticate(auth_header: str | None) -> Principal | None:if not auth_header or not auth_header.startswith("Bearer "):return Nonetoken = auth_header[len("Bearer "):]digest = hashlib.sha256(token.encode("utf-8")).hexdigest()return TOKEN_TABLE.get(digest)
Tokens have high entropy, so a direct dictionary lookup by digest is sufficient; there is no need for item-by-item comparison. If you are concerned about timing side channels, you can switch to hmac.compare_digest for per-entry comparison, but the benefit is limited for high-entropy tokens.
The key to access control is ordering. When different users can access different materials, permission tags must be written into each chunk at chunking time and applied before retrieval, rather than filtering content out after the answer is generated. The function below keeps only chunks whose tags intersect with the user’s groups.
def visible_chunks(chunks: list["Chunk"], groups: frozenset[str]) -> list["Chunk"]:return [c for c in chunks if c.acl & groups]
Chunks the user has no permission for never enter scoring, so they never appear in the prompt or in the source list. Tag mapping should follow a default-deny policy: files not found in the configuration get an empty tag set and are visible to no one.
Logs should record the time, user ID, question length, and matched sources for each query, but not the full question text or document content.
4. A Knowledge Base Built on Text Retrieval
4.1 Text Chunking
Matching against entire documents directly returns large amounts of irrelevant content. Chunking splits documents into small units suitable for inclusion in a prompt. This article uses a sliding window over lines, keeping a small overlap between adjacent chunks so that a paragraph split across a boundary does not lose key information. Each chunk carries its source path, starting line number, body text, and permission tags.
```python
import logging
import os
from dataclasses import dataclass
from typing import Callable
logger = logging.getLogger(“qa”)
MAXFILES = 5000
MAXFILE_BYTES = 2 1024 1024
SKIP_DIRS = {“.git”, “node_modules”, “__pycache“}
@dataclass
class Chunk:
source: str
line_start: int
text: str
acl: frozenset[str]
def load_chunks(
root: str,
acl_for: Callable[[str], frozenset[str]],
max_lines: int = 40,
overlap: int = 5,
) -> list[Chunk]:
chunks: list[Chunk] = []
step = max_lines - overlap
file_count = 0
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
for name in filenames:
if not name.endswith((“.md”, “.txt”)):
continue
file_count += 1
if file_count > MAX_FILES:
raise RuntimeError(“Knowledge base file count exceeded”)
