--- Semantic Document Retrieval • AI Security Cabinet

Semantic Document Retrieval

  • Turn each policy section and question into meaning-vectors and pick the closest match by angle—not proof that the winning section actually answers the question.

How it works

Keyword search only counts exact words, so asking about "home broadband" misses a policy that says "home internet". Semantic retrieval fixes that by asking a local embedding model (nomic-embed-text via Ollama) to turn text into a list of numbers (a vector) where similar meanings point in similar directions.

retrieve_semantic() in app/semantic_retrieval.py splits every .md file in data/policies on \n## into sections, embeds each section and the user’s question, and scores them with cosine_similarity(). If the best section scores at least min_score=0.60, it returns that section; otherwise it returns "No document found.".

What can go wrong

  • Zero-vector divide-by-zero: An all-zero vector makes np.linalg.norm zero. Guarding if denom == 0.0: return 0.0 prevents a NaN score (verified by unit test).
  • Entity-overlap trap: Asking "Is Northstar a Delaware-registered corporation?" matches a Northstar policy above 0.60 because of the shared entity name "Northstar", even though "Delaware" is nowhere in the text. A high similarity score still needs a grounded LLM prompt to say “not in the policy.”
  • Relative path assumption: policies_dir = Path("data/policies") assumes you run from the ai-security-lab root directory.
  • Re-embedding every query: Looping over every section and calling localhost:11434/api/embed on each request works for 3 small files, not a large corpus.

Referenced code

From app/semantic_retrieval.py in ai-security-lab:

policies_dir = Path("data/policies")

def generate_embedding(text: str) -> list[float]:
    url = "http://localhost:11434/api/embed"
    payload = {"model": "nomic-embed-text", "input": text}
    response = requests.post(url, json=payload, timeout=120)
    response.raise_for_status()
    return response.json()["embeddings"][0]

def cosine_similarity(vec_a: list[float], vec_b: list[float]) -> float:
    a = np.asarray(vec_a, dtype=float)
    b = np.asarray(vec_b, dtype=float)
    denom = np.linalg.norm(a) * np.linalg.norm(b)
    if denom == 0.0:
        return 0.0
    return float(np.dot(a, b) / denom)

def retrieve_semantic(query: str, min_score: float = 0.60) -> str:
    question_vector = generate_embedding(query)
    best_score = -1.0
    best_section = ""
    for file_path in policies_dir.glob("*.md"):
        if file_path.exists():
            for section in file_path.read_text().split("\n## "):
                score = cosine_similarity(generate_embedding(section), question_vector)
                if score > best_score:
                    best_score = score
                    best_section = section
    if best_score >= min_score:
        return best_section
    return "No document found."

Evidence: app/semantic_retrieval.py, app/main.py, data/policies/remote_work_policy.md, and tests/test_semantic_retrieval.py in ai-security-lab (3 unit tests passed locally without Ollama; 3 @pytest.mark.integration tests require a live localhost:11434 Ollama instance with nomic-embed-text). Related: Keyword document retrieval and RAG grounding.