Project 2: Company Knowledge-Base Assistant

Hybrid search, reranking and per-user access control over internal documents.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 24 · Lesson 3 of 7 · Intermediate

Project 2: Company Knowledge-Base Assistant

Hybrid search, reranking and per-user access control over internal documents.

This project builds a company knowledge-base assistant of the kind many organisations deploy internally. It answers employees' questions from internal documents with production-grade retrieval (hybrid search plus reranking) and, critically, respects document permissions so each employee only gets answers from documents they are allowed to read. It is served as an HTTP API.

Requirements

  • Documents in a folder, with a manifest that lists which groups may read each file.
  • Hybrid retrieval (BM25 + dense, fused with RRF) followed by a cross-encoder reranker.
  • Permission filtering applied before ranking, based on the authenticated user's groups.
  • Answers with citations, a clear "not found" response, and an API with a health check.
pip install fastapi uvicorn anthropic sentence-transformers rank-bm25 numpy

Project layout

kb_assistant/
  kb/                       # your documents (.txt or .md)
    leave-policy.md
    salary-bands-2026.md
    oncall-runbook.md
  kb/manifest.json          # file -> allowed groups
  users.json                # demo user directory (replace with your identity provider)
  kb_index.py               # indexing + retrieval
  kb_api.py                 # FastAPI service
kb/manifest.json
{
  "leave-policy.md":      ["all-staff"],
  "oncall-runbook.md":    ["engineering"],
  "salary-bands-2026.md": ["hr", "leadership"]
}
users.json
{
  "asha":  {"groups": ["all-staff", "engineering"]},
  "meera": {"groups": ["all-staff", "hr"]}
}

Indexing and retrieval

kb_index.py
import json
import re
from pathlib import Path
import numpy as np
from rank_bm25 import BM25Okapi
from sentence_transformers import CrossEncoder, SentenceTransformer

QUERY_PREFIX = "Represent this sentence for searching relevant passages: "

def tokenize(text: str) -> list[str]:
    return re.findall(r"[a-z0-9]+(?:-[a-z0-9]+)*", text.lower())

def split_markdown(text: str, max_chars: int = 1200) -> list[str]:
    """Split on headings, keep the heading path, then cap section size."""
    sections, heading, body = [], "", []
    for line in text.splitlines():
        if line.startswith("#"):
            if body:
                sections.append((heading, "\n".join(body).strip()))
            heading, body = line.lstrip("# ").strip(), []
        else:
            body.append(line)
    if body:
        sections.append((heading, "\n".join(body).strip()))
    chunks = []
    for h, b in sections:
        for i in range(0, len(b), max_chars):
            piece = b[i:i + max_chars].strip()
            if piece:
                chunks.append(f"{h}\n{piece}" if h else piece)
    return chunks

class KnowledgeBase:
    def __init__(self, folder: str = "kb"):
        manifest = json.loads(Path(folder, "manifest.json").read_text(encoding="utf-8"))
        self.chunks: list[dict] = []
        for name, groups in manifest.items():
            text = Path(folder, name).read_text(encoding="utf-8")
            for i, chunk in enumerate(split_markdown(text)):
                self.chunks.append({"id": f"{name}#{i}", "source": name,
                                    "text": f"[{name}]\n{chunk}", "groups": set(groups)})
        self.embedder = SentenceTransformer("BAAI/bge-small-en-v1.5")
        self.reranker = CrossEncoder("BAAI/bge-reranker-base")
        self.vectors = self.embedder.encode([c["text"] for c in self.chunks], normalize_embeddings=True)
        self.bm25 = BM25Okapi([tokenize(c["text"]) for c in self.chunks])

    def search(self, query: str, user_groups: set[str], k: int = 5, pool: int = 30) -> list[dict]:
        allowed = np.array([bool(c["groups"] & user_groups) for c in self.chunks])
        if not allowed.any():
            return []
        dense = self.vectors @ self.embedder.encode(QUERY_PREFIX + query, normalize_embeddings=True)
        sparse = self.bm25.get_scores(tokenize(query))
        dense[~allowed], sparse[~allowed] = -np.inf, -np.inf          # permission filter FIRST
        rankings = [list(np.argsort(-dense)[:pool]),
                    [i for i in np.argsort(-sparse)[:pool] if sparse[i] > 0]]
        fused: dict[int, float] = {}
        for ranking in rankings:
            for rank, i in enumerate(ranking, start=1):
                if allowed[i]:
                    fused[i] = fused.get(i, 0.0) + 1 / (60 + rank)
        candidates = sorted(fused, key=fused.get, reverse=True)[:pool]
        if not candidates:
            return []
        scores = self.reranker.predict([(query, self.chunks[i]["text"]) for i in candidates])
        ranked = sorted(zip(candidates, scores), key=lambda x: x[1], reverse=True)[:k]
        return [{**self.chunks[i], "score": float(s)} for i, s in ranked]

The API

kb_api.py
import json
from contextlib import asynccontextmanager
from pathlib import Path

import anthropic
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel, Field
from kb_index import KnowledgeBase

SYSTEM = """You are the internal knowledge assistant. Answer only from the sources provided,
citing the file name in square brackets after each statement, e.g. [leave-policy.md].
If the sources do not answer the question, reply exactly: "I couldn't find this in the
documents you have access to." Never speculate about documents you were not given."""
MIN_RERANK_SCORE = 0.05            # tune on your data
state = {}

@asynccontextmanager
async def lifespan(app):
    state["kb"] = KnowledgeBase("kb")
    state["users"] = json.loads(Path("users.json").read_text(encoding="utf-8"))
    state["llm"] = anthropic.Anthropic()
    yield

app = FastAPI(title="Knowledge Base Assistant", lifespan=lifespan)

class Question(BaseModel):
    question: str = Field(min_length=2, max_length=2000)

def current_groups(x_user: str | None) -> set[str]:
    # DEMO ONLY: in production, verify a session or token and read groups from your identity provider.
    user = state["users"].get(x_user or "")
    if not user:
        raise HTTPException(status_code=401, detail="Unknown user")
    return set(user["groups"])

@app.post("/ask")
def ask(q: Question, x_user: str | None = Header(default=None)):
    groups = current_groups(x_user)
    hits = [h for h in state["kb"].search(q.question, groups) if h["score"] >= MIN_RERANK_SCORE]
    if not hits:
        return {"answer": "I couldn't find this in the documents you have access to.", "sources": []}
    sources = "\n\n".join(f'<source file="{h["source"]}">\n{h["text"]}\n</source>' for h in hits)
    msg = state["llm"].messages.create(
        model="claude-opus-5-5", max_tokens=2000, output_config={"effort": "low"},
        system=[{"type": "text", "text": SYSTEM, "cache_control": {"type": "ephemeral"}}],
        messages=[{"role": "user", "content": f"<sources>\n{sources}\n</sources>\n\n{q.question}"}])
    answer = "".join(b.text for b in msg.content if b.type == "text")
    return {"answer": answer,
            "sources": sorted({h["source"] for h in hits}),
            "usage": {"input": msg.usage.input_tokens, "output": msg.usage.output_tokens}}

@app.get("/health")
def health():
    return {"status": "ok", "chunks": len(state["kb"].chunks)}

The endpoint is a regular (non-async) function because local embedding and reranking are CPU-bound; FastAPI runs such handlers in a thread pool so they do not block the server.

Try the permission boundary

uvicorn kb_api:app --port 8000
curl -X POST localhost:8000/ask -H "Content-Type: application/json" -H "X-User: asha" -d "{\"question\": \"What is the salary band for L4?\"}"
curl -X POST localhost:8000/ask -H "Content-Type: application/json" -H "X-User: meera" -d "{\"question\": \"What is the salary band for L4?\"}"

Asha (engineering) gets "I couldn't find this in the documents you have access to." Meera (HR) gets the answer with a citation. The salary document never reaches the model for Asha's request, because it is filtered out before ranking.

Extensions

  1. Replace the in-memory index with Qdrant and a MatchAny filter on allowed_groups (Access Control).
  2. Replace the X-User header with real authentication (OAuth / OpenID Connect) and group lookup.
  3. Add contextual retrieval at indexing time (Contextual Retrieval).
  4. Add the sync job from Re-Indexing, including permission changes.
  5. Add tracing, feedback and an audit log (Observability, Audit Trails).
  6. Write CI tests that assert restricted documents are never returned to the wrong groups.

Key takeaways

  • Production retrieval combines hybrid search, RRF and a reranker.
  • Permissions are applied before ranking, using groups from authentication, so restricted text never reaches the model.
  • A rerank-score threshold gives a reliable "not found" path.