Velamuvi AIAcademy

Lesson 16 of 16 · Projects

Project: AI Knowledge Base

Build an AI knowledge base with RAG: many sources, incremental syncing, access control per group, cited answers, logging, feedback and a production checklist.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Design a knowledge base that serves many documents, teams and users
  • Keep the index in sync as documents change, without re-embedding everything
  • Enforce access control so each user only retrieves what they may see
  • Log usage and feedback, and plan a launch with a production checklist

From one PDF to a whole organisation

The previous project answered questions about one file. A company knowledge base is the same pipeline with harder requirements:

  • Many sources: handbook, wiki pages, policies, FAQs, product docs, all changing at different times.
  • Many users with different permissions: not everyone may read salary bands or legal advice.
  • Trust: answers must cite sources, and the system must improve over time.

The core, in one class

This compact version brings together ideas from the whole course: chunking, hashes for incremental updates, deleting stale chunks, an access filter applied before ranking, a minimum score, and a grounded, numbered prompt:

Try it yourselfPython
import math, re

# ---- A tiny see-inside embedding model: one dimension per concept ----
CONCEPTS = {
    "leave":     "leave holiday holidays vacation annual time-off carried",
    "sick":      "sick ill illness unwell doctor self-certify",
    "remote":    "remote home hybrid office hours",
    "expenses":  "expenses expense claim reimbursed receipt receipts meals",
    "equipment": "laptop laptops monitor headset equipment lost stolen",
    "security":  "password passwords 2fa two-factor login phishing security",
    "parental":  "parental maternity paternity baby birth adoption adoptive",
    "training":  "training course courses learning books conferences",
    "travel":    "travel trip trips flight flights train trains journeys",
    "pay":       "pay paid salary payroll",
}
WORDS = {c: set(words.split()) for c, words in CONCEPTS.items()}

def words(text):
    return re.findall(r"[a-z0-9'-]+", text.lower())

def embed(text):
    v = [sum(w in WORDS[c] for w in words(text)) for c in CONCEPTS]
    length = math.sqrt(sum(x * x for x in v))
    return [x / length for x in v] if length else v

def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))       # vectors are unit length

import hashlib

class KnowledgeBase:
    def __init__(self):
        self.chunks = {}                                   # id -> chunk record

    def add_document(self, doc_id, title, text, access):
        """Split, embed and store a document. Unchanged chunks are skipped."""
        new_ids, embedded = set(), 0
        for i, part in enumerate(p.strip() for p in text.split("\n") if p.strip()):
            cid = f"{doc_id}:{i}"
            digest = hashlib.sha256(part.encode()).hexdigest()
            new_ids.add(cid)
            if cid in self.chunks and self.chunks[cid]["hash"] == digest:
                continue                                   # same text: no need to re-embed
            self.chunks[cid] = {"title": title, "text": part, "hash": digest,
                                "access": access, "vector": embed(title + ". " + part)}
            embedded += 1
        stale = [cid for cid in self.chunks if cid.startswith(doc_id + ":") and cid not in new_ids]
        for cid in stale:
            del self.chunks[cid]                           # paragraphs that were removed
        print(f"{doc_id}: embedded {embedded}, removed {len(stale)}")

    def search(self, question, user_groups, k=2, min_score=0.4):
        q = embed(question)
        allowed = [c for c in self.chunks.values() if c["access"] & user_groups]   # access filter FIRST
        ranked = sorted(allowed, key=lambda c: cosine(q, c["vector"]), reverse=True)[:k]
        return [c for c in ranked if cosine(q, c["vector"]) >= min_score]

    def prompt(self, question, user_groups):
        found = self.search(question, user_groups)
        if not found:
            return None
        sources = "\n".join(f"[{i}] {c['title']}: {c['text']}" for i, c in enumerate(found, start=1))
        return f"Answer only from the sources and cite them like [1].\n{sources}\nQuestion: {question}"

kb = KnowledgeBase()
kb.add_document("leave", "Leave policy", "Employees get 25 days of paid annual leave.\nUp to 5 unused days can be carried over.", {"everyone"})
kb.add_document("pay", "Salary bands", "Engineering salary bands are reviewed every April.", {"hr", "managers"})
kb.add_document("leave", "Leave policy", "Employees get 25 days of paid annual leave.\nUp to 8 unused days can be carried over.", {"everyone"})

print()
print(kb.prompt("How many leave days can I carry over?", {"everyone"}))
print()
for groups in [{"everyone"}, {"everyone", "managers"}]:
    print("Asked by", sorted(groups), "->")
    print(kb.prompt("When are salary bands reviewed?", groups) or "No sources this user may see: reply that you couldn't find it.")

Read the output from the top:

  • Re-adding the updated leave policy embedded just one chunk: the unchanged sentence was skipped, and the new “8 days” rule replaced the old one.
  • The leave question retrieved the new rule first, ready for a cited answer.
  • The salary bands document is only visible to HR and managers. An ordinary employee's search never even sees it, so their assistant honestly reports that nothing was found; a manager gets the answer.

Architecture of a real deployment

PartWhat it doesExample choices
ConnectorsFetch documents and permissions from each source on a scheduleWiki, file storage and ticketing APIs
Ingestion workerClean, chunk, hash, embed changed chunks, delete removed onesA scheduled job or queue worker
Vector storeChunks, vectors and metadata (source, URL, updated, access groups)pgvector, Qdrant, Pinecone and others
Query serviceRewrite, hybrid retrieve with access filter, rerank, prompt, generateA small API service
AppChat interface showing answers with clickable citations, thumbs up and downWeb app, chat-tool integration
Logs and evaluationStore questions, retrieved chunks, answers and feedback; run the test setA database plus scheduled evaluation

Learn from usage

Logs turn a knowledge base from a demo into a product. Each week, look at the questions with no sources found (missing content), the thumbs-down answers (triage them as in the failures lesson), and the most-asked questions (make sure those documents are excellent).

Production checklist

  • Content: owners for each source; outdated documents removed; tables and scans handled.
  • Ingestion: stable IDs, hashes, deletes, scheduled syncs, alerts when a sync fails.
  • Retrieval: access filters, hybrid search, reranking, minimum score, measured on a test set.
  • Generation: grounded prompt, exact fallback, citations checked in code, sources treated as untrusted.
  • Operations: logging, feedback, cost and response-time monitoring, a regular evaluation run.
  • People: clear notice that answers come from AI, links to the sources, an easy path to a human.

Common mistakes

Practice exercise

Turn usage logs into a weekly report: how satisfied are users, and which questions does the knowledge base not cover yet?

Your solutionPython
# One week of logs from the knowledge base
log = [
    {"question": "How many leave days do I get?", "found": True,  "thumbs_up": True},
    {"question": "Is there a gym?",               "found": False, "thumbs_up": False},
    {"question": "When is payday?",               "found": False, "thumbs_up": False},
    {"question": "Can I work from home?",         "found": True,  "thumbs_up": True},
    {"question": "What's the laptop policy?",     "found": True,  "thumbs_up": False},
]

# Print the share of answers with a thumbs up, then every question with no sources found
# (these show what content is missing):
# Thumbs up: 40%
# Missing content: Is there a gym?
# Missing content: When is payday?
Knowledge check

In a company knowledge base, when should the access filter be applied?

Summary

  • A knowledge base is the RAG pipeline plus many sources, permissions and continuous improvement.
  • Incremental sync with stable IDs and hashes keeps the index current cheaply, including deletes.
  • Access filters come from source systems and apply during retrieval, on every query.
  • Logs, feedback and a test set show what to fix; launch small and grow.

Course complete

You can now build retrieval-augmented generation systems end to end: load and chunk documents, embed and index them, retrieve with hybrid search, reranking and query rewriting, write grounded prompts with citations, and measure and fix what goes wrong. Natural next steps are LLM application development (turning this into a polished product) and LLM evaluation (measuring quality at scale).

Finished reading? Tick it off to track your progress.