Skip to main content

Turn a whole book into a queryable knowledge graph in Python

Python
OKF
DuckDB
RAG
knowledge graph

Forty lines of Python convert Christoph Molnar’s Interpretable Machine Learning into an Open Knowledge Format bundle. okf-ingest then loads it into DuckDB, checks it, draws the graph and searches it. No agent in the loop.

Author

Travis Jakel

Published

November 30, 2026

A long technical book is good to read and awkward to query. Which chapters cover local explanation methods? Where exactly is the Shapley value explanation? What links to what? This post turns a book into a small knowledge graph you can run SQL and semantic search against, deterministically, with no language model deciding what the structure is.

The book is Christoph Molnar’s Interpretable Machine Learning, whose Quarto sources are public under CC BY-NC-SA. The tool is okf-ingest, which reads an Open Knowledge Format bundle into a DuckDB catalog. Disclosure: I wrote okf-ingest.

OKF itself is a short convention. A bundle is a folder of markdown files, one concept per file, each with YAML frontmatter. The only required field is type. Ordinary markdown links are the graph. Two filenames are reserved: index.md, the map, and log.md, the history.

Step 1: install, and get the book

pip install okf-ingest
git clone --depth 1 https://github.com/christophM/interpretable-ml-book src

Step 2: make it OKF

This is the only conversion step. The book is 47 Quarto chapters grouped into Parts. Each chapter becomes a concept whose type is its Part, with a title and a one-sentence description taken from its first line of prose. Each Part becomes a concept that links to its chapters, and index.md links to the Parts, so the folder has a real graph instead of a flat list.

import os, re, shutil
SRC, OUT, AT = "src/manuscript", "iml-okf", "2026-07-07T00:00:00Z"   # the book's last commit
PARTS = {
  "Foundations": ["intro","interpretability","goals","overview","data"],
  "Interpretable Models": ["limo","logistic","extend-lm","tree","rules","rulefit"],
  "Local Model-Agnostic Methods": ["ceteris-paribus","ice","lime","counterfactual","anchors","shapley","shap"],
  "Global Model-Agnostic Methods": ["pdp","ale","interaction","decomposition","feature-importance","lofo","global","proto"],
  "Neural Network Interpretation": ["cnn-features","pixel-attribution","detecting-concepts","adversarial","influential"],
  "Beyond the Methods": ["evaluation","storytime","future","translations"],
  "Back Matter": ["cite","acknowledgements"],
  "Appendix": ["what-is-machine-learning","math-terms","r-packages","references"],
}
shutil.rmtree(OUT, ignore_errors=True); os.makedirs(OUT)
pslug = lambda p: "part-" + re.sub(r"[^a-z0-9]+", "-", p.lower())
yq = lambda s: "'" + s.replace("'", "''") + "'"         # YAML single-quoted string

def clean(lines):                                       # keep prose; links come from structure
    out = []
    for ln in lines:
        if re.match(r"^\s*(\{\{<|:::)", ln): continue   # drop Quarto directives
        ln = re.sub(r"\s*\{#[^}]+\}\s*$", "", ln)       # strip {#label} from headings
        ln = re.sub(r"!\[[^]]*\]\([^)]*\)", "", ln)     # remove image embeds
        out.append(re.sub(r"\[([^]]+)\]\([^)]*\)", r"\1", ln))  # de-link to prose
    return out

def first_sentence(body):                               # becomes the description
    for ln in body:
        if ln.strip() and not ln.startswith("#"):
            return re.sub(r"([.!?]).*$", r"\1", ln.strip())[:200]
    return ""

def fm(type_, title, desc):
    return ["---", f"type: {type_}", f"title: {yq(title)}", f"description: {yq(desc)}",
            f'generated: {{ by: "process:convert", at: "{AT}" }}',
            "tags: [interpretable-ml]", "---", ""]

def write(name, lines):
    with open(os.path.join(OUT, name), "w", encoding="utf-8", newline="\n") as fh:
        fh.write("\n".join(lines) + "\n")

for part, stubs in PARTS.items():                       # one concept per chapter
    for stub in stubs:
        raw = open(os.path.join(SRC, stub + ".qmd"), encoding="utf-8").read().splitlines()
        h1 = next((l for l in raw if re.match(r"^#\s", l)), "# " + stub)
        title = re.sub(r"\{#[^}]+\}", "", re.sub(r"^#\s+", "", h1)).strip()
        body = clean(raw)
        write(stub + ".md", fm(part, title, first_sentence(body)) + body)

for part, stubs in PARTS.items():                       # one concept per Part, linking its chapters
    write(pslug(part) + ".md", fm("Part", part, f"Chapters in the {part} part.") +
          [f"# {part}", ""] + [f"- [{s}]({s}.md)" for s in stubs])

write("index.md", ["---", 'okf_version: "0.3"', "title: Interpretable Machine Learning",   # bundle metadata
                   "description: Christoph Molnar's book on making black box models explainable, one concept per chapter.",
                   "license: CC-BY-NC-SA-4.0", "---", "",
                   "# Interpretable Machine Learning", ""] + [f"- [{p}]({pslug(p)}.md)" for p in PARTS])
write("log.md", ["# Bundle history", "", "## 2026-11-30", "",
                 "- Converted from the Quarto sources of *Interpretable Machine Learning*."])

Two details follow OKF v0.3. The root index.md carries bundle metadata, including the book’s licence. And log.md has no frontmatter and dates its entries with ## YYYY-MM-DD headings; a log with frontmatter is a conformance error in v0.3.

Step 3: validate and ingest

okf validate iml-okf
#> bundle: iml-okf
#> conformant: True  (errors: 0, warnings: 0)

okf ingest iml-okf --db iml.duckdb
#> ingested iml-okf -> iml.duckdb
#>   concepts=49 conformant=49 (True) errors=0 warnings=0 links=49 broken=0

49 concepts: 41 chapters and 8 Part pages. The same thing from Python returns an open DuckDB connection, and from there it is plain SQL:

import okf
con, summary = okf.ingest("iml-okf", db_path="iml.duckdb")

con.execute("""SELECT type, count(*) n FROM okf_concept WHERE reserved = FALSE
               GROUP BY type ORDER BY n DESC, type""").fetchall()
#> [('Global Model-Agnostic Methods', 8), ('Part', 8), ('Local Model-Agnostic Methods', 7), ('Interpretable Models', 6), ('Foundations', 5), ('Neural Network Interpretation', 5), ('Appendix', 4), ('Beyond the Methods', 4), ('Back Matter', 2)]

con.execute("""
    SELECT c.title, length(c.body) AS chars
    FROM okf_concept c
    WHERE c.type = 'Local Model-Agnostic Methods'
    ORDER BY chars DESC
""").df()
#>                                    title  chars
#>                                     LIME  31456
#>                                     SHAP  31424
#>              Counterfactual Explanations  28784
#>                           Shapley Values  25364
#>                   Scoped Rules (Anchors)  20175
#>                    Ceteris Paribus Plots  14358
#> Individual Conditional Expectation (ICE)   9330

Step 4: health check

okf doctor goes past conformance: orphans, missing recommended fields, stale timestamps, links to deprecated concepts.

okf doctor iml-okf
#> health: 100/100  (49/49 concepts clean · 0 errors · 0 warnings)

That score is earned by the converter. My first version of it wrote no description, and the same command reported 49 warnings and a health of 0/100. The check is cheap enough to run in CI on every change to a bundle.

Step 5: see it

okf graph iml-okf --out iml-graph.html
#> [graph_html] wrote iml-graph.html (51 nodes, 49 edges)

The book as a graph: the index in the centre, eight Part hubs around it, chapters coloured by Part. The stray dot at the lower right is log.md, which nothing links to.

The output is one self-contained HTML page of about 17 KB with no external scripts. You can pan, zoom and search it.

Step 6: ask it a question

Embedding is the one place a model is used, and it is optional. okf.embed() chunks the chapter text and embeds it with a local model (Ollama’s nomic-embed-text by default), storing the vectors in the same DuckDB file.

print(okf.embed(con), "chunks embedded")
for path, title, chunk, score, text in okf.rag_search(
        con, "How are Shapley values used to explain a prediction?", k=4):
    print(f"[{score:.3f}] {path}#{chunk}  {title}")
#> 1369 chunks embedded
#> [0.852] shapley.md#1  Shapley Values
#> [0.848] shapley.md#38  Shapley Values
#> [0.846] shapley.md#21  Shapley Values
#> [0.844] shapley.md#11  Shapley Values

All four hits are passages of the Shapley Values chapter, ahead of the SHAP chapter that builds on it.

Why not let a model read the book?

Because nothing here asks a model what the structure is. The graph is exactly the structure the author wrote down in the book’s table of contents. The same sources always give the same catalog, the same graph and the same health score, which means you can assert on them in a test. A model enters only at the embedding step, and only if you want it.

The same bundle can be built and read from R with the okf package. I ran the R version of this converter on the same book: it wrote the same 51 files, byte for byte, and gave the same counts, health score and search hits. A companion post covers that side.


okf-ingest is open source (Apache-2.0): GitHub, PyPI. The book is Interpretable Machine Learning by Christoph Molnar, used here under CC BY-NC-SA for demonstration. The converted bundle is not redistributed; the code above rebuilds it from the author’s repository. Read the real thing at https://christophm.github.io/interpretable-ml-book/.

Run with okf-ingest 0.14.2 on Python 3.12.10, against the book repository at commit 8f470c8 (2026-07-07). Embeddings came from nomic-embed-text on a local server. The script that produced every output above is in this blog’s repository under _runs/okf_py_book.py.