{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "12bfea7d",
   "metadata": {},
   "source": [
    "# 🌌 Embeddings in Python\n",
    "\n",
    "An **embedding** turns a text into a list of numbers, in such a way that texts with a similar meaning get similar numbers (see the chapter [Embeddings](https://ai.kuleuven.be/aivooriedereen/embeddings)). In this notebook you put that to work on a text you know well: this course. You draw a map of all its sections, you let the computer find its topics without telling it what the chapters are, and you build a search engine that searches on meaning instead of on words.\n",
    "\n",
    "You will:\n",
    "\n",
    "1. 🔢 turn sentences into numbers, and see which ones lie close together;\n",
    "2. 📚 collect the text of the course and cut it into pieces;\n",
    "3. 🗺️ draw a map of the course, and let 🫧 k-means and 🌲 hierarchical clustering find its topics;\n",
    "4. 🔍 search the course on meaning;\n",
    "5. 🤖 as an extra, build a study assistant that looks things up in the course before it answers.\n",
    "\n",
    "**Prior knowledge**: the chapter [Embeddings](https://ai.kuleuven.be/aivooriedereen/embeddings), and [k-means](https://ai.kuleuven.be/aivooriedereen/en/clustering#k-means-clustering) and [hierarchical clustering](https://ai.kuleuven.be/aivooriedereen/en/clustering#hierarchical-clustering) from the chapter Clustering. The extra part at the end builds on [tool calling](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#tool-calling) from the chapter Large language models.\n",
    "\n",
    "**Estimated time**: about 40 minutes. Everything runs on Colab's free computer; only the extra part needs a free key from OpenRouter.\n",
    "\n",
    "*This notebook is part of [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en) (KU Leuven). The latest version is always at [ai.kuleuven.be/aivooriedereen/en/notebook/embeddings](https://ai.kuleuven.be/aivooriedereen/en/notebook/embeddings), and you can open it directly in [Google Colab](https://colab.research.google.com/drive/1CWPS713PKVQlgvqe4VtuIhdDFkROWsNI?usp=sharing).*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "122a045c",
   "metadata": {},
   "source": [
    "## 🚀 First time in a notebook?\n",
    "\n",
    "Then the short [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains everything step by step. The most important things:\n",
    "\n",
    "1. **Make your own copy**: *File → Save a copy in Drive* (in the menu at the top left), and work in that copy.\n",
    "2. **Run a cell** by clicking in it and pressing **Shift+Enter**, or with the ▶ button to its left. The result appears below the cell.\n",
    "3. **Run the cells in order, from top to bottom**, because a cell uses what the cells above it made. Does something behave strangely? Choose *Runtime → Restart session* and run everything again from the top.\n",
    "\n",
    "**Prefer not to use Google?** Download [the notebook file](https://ai.kuleuven.be/aivooriedereen/notebooks/embeddings.ipynb) and open it in [Jupyter](https://jupyter.org/install) or [Visual Studio Code](https://code.visualstudio.com/docs/datascience/jupyter-notebooks). For the extra part at the end, put your OpenRouter key in an environment variable `OPENROUTER_API_KEY`, or type it in when the notebook asks for it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70d7691d",
   "metadata": {},
   "source": [
    "## 🐍 Python in this notebook\n",
    "\n",
    "New to Python? The [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains the basics: variables, lists, loops and functions. On top of those, this notebook uses:\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `model.encode(texts)` | Turns a list of texts into a table of numbers: one row, a vector, per text. |\n",
    "| `vectors @ vectors.T` | A matrix product: the dot product of every vector with every other vector, all at once. |\n",
    "| `np.argsort(-scores)[:5]` | The positions of the five highest scores. |\n",
    "| `requests.get(url).text` | Downloads a web page, as text in HTML. |\n",
    "| `BeautifulSoup(page, \"html.parser\")` | Reads that HTML, so that you can ask for parts of the page, such as `.find(\"article\")` or `.find_all(\"h2\")`. |\n",
    "| `re.findall(r\"...\", text)` | Finds every piece of a text that matches a pattern (a regular expression). |\n",
    "| `pd.DataFrame(rows)` | A table made from a list of dictionaries, one row per dictionary. `table[table.chapter == name]` keeps the rows you want. |\n",
    "| `px.scatter(table, x=\"x\", y=\"y\", color=\"chapter\")` | An interactive plot (plotly): hover over a dot to see what it is. |\n",
    "| `question = \"...\"  # @param {type:\"string\"}` | In Colab, a text field next to the code, as in the introductory notebook. |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2325f5cd",
   "metadata": {},
   "source": [
    "## 🔢 Sentences as numbers\n",
    "\n",
    "An embedding model reads a text and returns a **vector**: a fixed list of numbers. This notebook uses [granite-embedding-107m-multilingual](https://huggingface.co/ibm-granite/granite-embedding-107m-multilingual), a small model from IBM (107 million weights) that knows twelve languages, among them English and Dutch, and that runs fine on Colab's computer without a graphics card. The first time, Colab downloads it: about 230 MB."
   ]
  },
  {
   "cell_type": "code",
   "id": "d499f3f3",
   "metadata": {},
   "source": [
    "# Colab already has these packages; elsewhere, this installs them\n",
    "%pip install --quiet sentence-transformers plotly beautifulsoup4 openai markdown"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "8c008029",
   "metadata": {},
   "source": [
    "import getpass\n",
    "import html\n",
    "import json\n",
    "import os\n",
    "import re\n",
    "import textwrap\n",
    "\n",
    "import markdown\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import plotly.express as px\n",
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "from IPython.display import HTML, display\n",
    "from openai import OpenAI\n",
    "from scipy.cluster.hierarchy import dendrogram, linkage\n",
    "from sentence_transformers import SentenceTransformer\n",
    "from sklearn.cluster import KMeans\n",
    "from sklearn.manifold import TSNE"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "2ccb5527",
   "metadata": {},
   "source": [
    "model = SentenceTransformer(\"ibm-granite/granite-embedding-107m-multilingual\")\n",
    "model.float()   # ordinary floats: the model is stored in a shorter number format that many processors compute slowly\n",
    "\n",
    "vector = model.encode(\"The train to Leuven is late again.\")\n",
    "print(vector.round(3))\n",
    "print(\"Size of the vector:\", vector.shape)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "53b2ee96",
   "metadata": {},
   "source": [
    "One sentence, **384 numbers**. On their own they mean nothing to you, and that's fine: what matters is which vectors lie close to each other. As a measure, this notebook uses the **cosine similarity**: 1 when two vectors point in the same direction, around 0 when they have nothing to do with each other. With `normalize_embeddings=True`, every vector gets length 1, and then the cosine similarity is simply the dot product `a @ b`. For a whole list of vectors, `vectors @ vectors.T` gives every pair at once:"
   ]
  },
  {
   "cell_type": "code",
   "id": "7308ba9f",
   "metadata": {},
   "source": [
    "sentences = [\n",
    "    \"The train to Leuven is late again.\",\n",
    "    \"My bus never shows up on time.\",\n",
    "    \"It will rain all day tomorrow.\",\n",
    "    \"Take an umbrella, a storm is coming.\",\n",
    "    \"The exam was much harder than I expected.\",\n",
    "    \"I failed my statistics test.\",\n",
    "    \"De trein naar Leuven heeft weer vertraging.\",\n",
    "]\n",
    "vectors = model.encode(sentences, normalize_embeddings=True)\n",
    "similarity = vectors @ vectors.T\n",
    "\n",
    "figure, axes = plt.subplots(figsize=(8, 4.5))\n",
    "axes.imshow(similarity, cmap=\"Blues\", vmin=0.4, vmax=1)\n",
    "for row in range(len(sentences)):\n",
    "    for column in range(len(sentences)):\n",
    "        value = similarity[row, column]\n",
    "        axes.text(column, row, f\"{value:.2f}\", ha=\"center\", va=\"center\", fontsize=9, color=\"white\" if value > 0.8 else \"black\")\n",
    "axes.set_xticks(range(len(sentences)), [str(number) for number in range(1, len(sentences) + 1)])\n",
    "axes.set_yticks(range(len(sentences)), [f\"{number}. {sentence}\" for number, sentence in enumerate(sentences, 1)])\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "7e259a59",
   "metadata": {},
   "source": [
    "Every sentence is most similar to the other one on the same topic, also when they share hardly any words, like *late again* and *never shows up on time*. That's what a search on keywords can't do. The Dutch sentence lands right on top of its English translation (**0.91**): the model learned both languages in one space. And notice that no score comes near 0. Even sentences about different topics score around 0.5 here: only the order counts, and every model has a scale of its own.\n",
    "\n",
    "Now one word with two meanings, and one sentence turned around:"
   ]
  },
  {
   "cell_type": "code",
   "id": "5dded443",
   "metadata": {},
   "source": [
    "def similarity_of(a, b):\n",
    "    # How close two texts lie: the cosine similarity of their vectors\n",
    "    vector_a, vector_b = model.encode([a, b], normalize_embeddings=True)\n",
    "    return float(vector_a @ vector_b)\n",
    "\n",
    "\n",
    "pairs = [\n",
    "    (\"She sat on the bank of the river.\", \"She sat by the water.\"),\n",
    "    (\"She sat on the bank of the river.\", \"She took money out of the bank.\"),\n",
    "    (\"I really like this course.\", \"This course is great fun.\"),\n",
    "    (\"I really like this course.\", \"I don't like this course at all.\"),\n",
    "]\n",
    "for a, b in pairs:\n",
    "    print(f\"{similarity_of(a, b):.2f}   {a}  |  {b}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "dc214ead",
   "metadata": {},
   "source": [
    "The bank of a river lands closer to *the water* than to the bank where you take out money: the model reads the whole sentence, not only the word. But in the last two lines it goes wrong: *I don't like this course at all* scores **higher** than *This course is great fun*. Both sentences are about liking this course, and the *don't* hardly counts. An embedding captures what a text is **about** much better than what it **claims**. Keep that in mind for the search engine later: it finds the sections on the right topic, but you (or a language model) still have to read what they say."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60426315",
   "metadata": {},
   "source": [
    "## 📚 The course as data\n",
    "\n",
    "Now a real text: the course itself. Every chapter is a web page, and every heading on it has an address of its own, such as `…/en/history#the-first-ai-winter`. Which chapters are there? Most websites list their pages for search engines in a file [sitemap.xml](https://www.sitemaps.org/). This cell keeps the English chapters from it:"
   ]
  },
  {
   "cell_type": "code",
   "id": "fdb5439e",
   "metadata": {},
   "source": [
    "SITE = \"https://ai.kuleuven.be/aivooriedereen\"\n",
    "# Tells the website who is asking. Reusing this code for another website? Then describe yourself instead.\n",
    "HEADERS = {\"User-Agent\": \"Student running the AI voor Iedereen embeddings notebook \"\n",
    "                         \"(https://ai.kuleuven.be/aivooriedereen/en/notebook/embeddings)\"}\n",
    "\n",
    "sitemap = requests.get(f\"{SITE}/sitemap.xml\", headers=HEADERS).text\n",
    "chapters = [path for path in re.findall(r\"aivooriedereen(/en/[a-z-]+)</loc>\", sitemap)\n",
    "            if path not in (\"/en/demo\", \"/en/notebook\", \"/en/about\")]\n",
    "print(len(chapters), \"chapters:\", \" \".join(chapters))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ee19b78f",
   "metadata": {},
   "source": [
    "A web page is written in HTML: text between tags, such as `<h2>` for a heading and `<p>` for a paragraph. `read_chapter` takes the `<article>` out of a chapter page (the text, without menus and buttons), turns every formula back into the LaTeX it was written in, and cuts the text at every heading. Every section keeps its link: the address of the page, with the id of its heading after the `#`."
   ]
  },
  {
   "cell_type": "code",
   "id": "892f6f74",
   "metadata": {},
   "source": [
    "def read_chapter(path):\n",
    "    # The sections of one chapter: the text under every heading, with its chapter, heading and link\n",
    "    page = BeautifulSoup(requests.get(SITE + path, headers=HEADERS).content, \"html.parser\")  # the bytes: the page says how to read them\n",
    "    article = page.find(\"article\")                                     # the chapter itself, without menus\n",
    "    for tag in article.find_all([\"script\", \"style\", \"svg\", \"button\"]) + article.find_all(class_=\"sr-only\"):\n",
    "        tag.decompose()                                                  # no code, drawings, buttons or text for screen readers\n",
    "    for formula in article.find_all(class_=\"katex\"):                    # a formula: keep the LaTeX\n",
    "        latex = formula.find(\"annotation\")\n",
    "        formula.replace_with(f\"${latex.get_text()}$\" if latex else \"\")\n",
    "    for cell in article.find_all([\"td\", \"th\"]):\n",
    "        cell.append(\" | \")                                               # a table: keep its cells apart\n",
    "    for block in article.find_all([\"p\", \"div\", \"li\", \"tr\", \"figcaption\", \"blockquote\"]):\n",
    "        block.append(\"\\n\")                                               # a new line after every paragraph\n",
    "    chapter = article.find(\"h1\").get_text(\" \", strip=True)\n",
    "    for heading in article.find_all([\"h2\", \"h3\", \"h4\", \"h5\"]):          # mark every heading in the text\n",
    "        heading.replace_with(f\"\\n@@{heading.get('id')}@@{heading.get_text(' ', strip=True)}\\n\")\n",
    "    parts = re.split(r\"\\n@@(.*?)@@(.*)\\n\", article.get_text())           # and cut the text at those marks\n",
    "    sections = []\n",
    "    for anchor, heading, text in zip(parts[1::3], parts[2::3], parts[3::3]):\n",
    "        text = re.sub(r\"[ \\t]+\", \" \", text)\n",
    "        text = re.sub(r\"\\s*\\n\\s*\", \"\\n\", text).strip()                  # no empty lines\n",
    "        sections.append({\"chapter\": chapter, \"heading\": heading, \"url\": f\"{SITE}{path}#{anchor}\", \"text\": text})\n",
    "    return sections\n",
    "\n",
    "\n",
    "sections = pd.DataFrame([section for path in chapters for section in read_chapter(path)])\n",
    "print(len(sections), \"sections,\", sections.text.str.split().str.len().sum(), \"words\")\n",
    "examples = sections[sections.text != \"\"].head(3)\n",
    "HTML(examples.assign(text=examples.text.str[:150].str.replace(\"\\n\", \" \") + \" …\").to_html(index=False))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ac3e2c64",
   "metadata": {},
   "source": [
    "Most sections are a few paragraphs long, but some run to more than 800 words. That's a problem for two reasons. The model only reads the first 512 [tokens](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#tokens-large-language-models-do-not-see-letters) of a text (roughly 400 words), and silently ignores the rest. And one vector for a long section about three things is a blur of all three. So the long sections are cut into **chunks** of at most 200 words, between two paragraphs. Every chunk also gets its heading in front, so that a chunk that starts with *That's why …* still says what it's about. Not the name of its chapter, though: you'll see why in the part about k-means.\n",
    "\n",
    "Libraries such as LangChain (`RecursiveCharacterTextSplitter`) and chonkie do the same: they cut at the largest boundary that still fits, a paragraph, then a sentence, then a word. Some can also cut on meaning, wherever two sentences in a row lie far apart. On the English chapters of this course, such a *semantic chunker* found only **14%** of the places where the authors put a heading; cutting at random found 8%. For a text with headings, the headings are the better cut. Semantic chunking is for text without any structure, such as the transcript of a lecture."
   ]
  },
  {
   "cell_type": "code",
   "id": "3a555a74",
   "metadata": {},
   "source": [
    "def cut(text, max_words=200):\n",
    "    # A long text in pieces of at most max_words words, cut between two paragraphs\n",
    "    pieces, current = [], []\n",
    "    for paragraph in text.split(\"\\n\"):\n",
    "        if current and len(\" \".join(current + [paragraph]).split()) > max_words:\n",
    "            pieces.append(\"\\n\".join(current))\n",
    "            current = []\n",
    "        current.append(paragraph)\n",
    "    return pieces + [\"\\n\".join(current)]\n",
    "\n",
    "\n",
    "chunks = []\n",
    "for section in sections.itertuples():\n",
    "    if len(section.text.split()) < 15:                                  # only a heading, the text sits below the next one\n",
    "        continue\n",
    "    for piece in cut(section.text):\n",
    "        chunks.append({\"chapter\": section.chapter, \"heading\": section.heading, \"url\": section.url,\n",
    "                       \"text\": f\"{section.heading}\\n{piece}\"})\n",
    "chunks = pd.DataFrame(chunks)\n",
    "words = chunks.text.str.split().str.len()\n",
    "print(len(chunks), \"chunks, median\", int(words.median()), \"words, the longest\", words.max())"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "02302d9d",
   "metadata": {},
   "source": [
    "Now every chunk becomes a vector. That's the slowest step of the notebook: about a minute on Colab's computer."
   ]
  },
  {
   "cell_type": "code",
   "id": "6b7af21e",
   "metadata": {},
   "source": [
    "vectors = model.encode(chunks.text.tolist(), normalize_embeddings=True, batch_size=16)\n",
    "print(vectors.shape)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "fc12664c",
   "metadata": {},
   "source": [
    "## 🗺️ A map of the course\n",
    "\n",
    "Every chunk is now a point in a space of 384 dimensions. To see them, **[t-SNE](https://distill.pub/2016/misread-tsne/)** squashes those 384 numbers into 2, and tries to keep points that were neighbors close together on the map. It's a picture for your eyes, not something to compute with: the size of an island and the distance between two islands mean little. `draw_map` draws one dot per chunk, with the name of every chapter in the middle of its dots. Hover over a dot to see its heading and its first words."
   ]
  },
  {
   "cell_type": "code",
   "id": "a93fd713",
   "metadata": {},
   "source": [
    "xy = TSNE(n_components=2, metric=\"cosine\", random_state=0).fit_transform(vectors)\n",
    "chunks[\"x\"], chunks[\"y\"] = xy[:, 0], xy[:, 1]\n",
    "chunks[\"preview\"] = [html.escape(textwrap.fill(text.split(\"\\n\")[1][:150], 60)).replace(\"\\n\", \"<br>\") + \" …\" for text in chunks.text]\n",
    "\n",
    "\n",
    "def draw_map(color):\n",
    "    # The map of the course: a dot per chunk, colored by the column `color`, with every chapter's name in the middle of its dots\n",
    "    figure = px.scatter(chunks, x=\"x\", y=\"y\", color=color, hover_name=\"heading\", height=390, template=\"plotly_white\",\n",
    "                        hover_data={\"chapter\": True, \"preview\": True, \"x\": False, \"y\": False},\n",
    "                        color_discrete_sequence=px.colors.qualitative.Dark24)\n",
    "    for name, middle in chunks.groupby(\"chapter\")[[\"x\", \"y\"]].mean().iterrows():\n",
    "        figure.add_annotation(x=middle.x, y=middle.y, text=name, showarrow=False, font_size=11, bgcolor=\"rgba(255,255,255,0.7)\")\n",
    "    figure.update_layout(showlegend=False, xaxis_visible=False, yaxis_visible=False, margin=dict(l=0, r=0, t=0, b=0))\n",
    "    figure.show()\n",
    "\n",
    "\n",
    "draw_map(\"chapter\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "1955bcc7",
   "metadata": {},
   "source": [
    "Most chapters form an island of their own, and nobody told the model which chunk belongs to which chapter: it only read the text. Where two islands touch, the chapters share a topic.\n",
    "\n",
    "Not every chapter forms an island. The soft pink dots of **Dimensions of AI** are spread all over the map: that chapter gives an overview of the whole field, and many of its parts land next to the chapter that goes deeper into their topic. Hover over them: the Analogizers lie next to Nearest Neighbors, the Bayesians next to Probability, and reinforcement learning next to Game Trees.\n",
    "\n",
    "One spot looks odd: a tight knot of dots in many colors. Hover over it: it's the feedback form at the end of every chapter, every time the same text, so every time the same vector. A map like this is a quick way to find such duplicates in your data. They don't belong in a search engine, so out they go:"
   ]
  },
  {
   "cell_type": "code",
   "id": "967200df",
   "metadata": {},
   "source": [
    "feedback = chunks.heading.str.endswith(\"Feedback\").to_numpy()\n",
    "print(feedback.sum(), \"chunks are the feedback form\")\n",
    "vectors, chunks = vectors[~feedback], chunks[~feedback].reset_index(drop=True)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "1388af19",
   "metadata": {},
   "source": [
    "## 🫧 Topics with k-means\n",
    "\n",
    "Now the computer looks for groups itself, with [k-means](https://ai.kuleuven.be/aivooriedereen/en/clustering#k-means-clustering) from the chapter Clustering. It works on all 384 numbers of every chunk, not on the squashed map. For *k*, take the number of chapters: then you can check whether k-means finds the chapters again. To see what a cluster is about, it gets the heading of the chunk closest to its center as its name."
   ]
  },
  {
   "cell_type": "code",
   "id": "70e6adf0",
   "metadata": {},
   "source": [
    "k = chunks.chapter.nunique()\n",
    "kmeans = KMeans(n_clusters=k, n_init=10, random_state=0).fit(vectors)\n",
    "\n",
    "topics = {}\n",
    "for cluster in range(k):\n",
    "    members = np.flatnonzero(kmeans.labels_ == cluster)\n",
    "    closest = members[np.argmax(vectors[members] @ kmeans.cluster_centers_[cluster])]\n",
    "    name = chunks.heading[closest]\n",
    "    topics[cluster] = name if name not in topics.values() else f\"{name} ({cluster})\"   # two clusters, one name\n",
    "chunks[\"topic\"] = [topics[cluster] for cluster in kmeans.labels_]\n",
    "\n",
    "rows = []\n",
    "for topic, group in chunks.groupby(\"topic\"):\n",
    "    counts = group.chapter.value_counts()\n",
    "    rows.append({\"topic\": topic, \"chunks\": len(group), \"mostly from\": counts.index[0], \"own\": counts.iloc[0]})\n",
    "overview = pd.DataFrame(rows)\n",
    "overview[\"share\"] = overview.own / overview.chunks\n",
    "print(f\"{overview.own.sum() / len(chunks):.0%} of the chunks are in a cluster that mostly holds their own chapter\")\n",
    "overview = overview.sort_values(\"share\", ascending=False).drop(columns=\"own\")\n",
    "HTML(overview.to_html(index=False, formatters={\"share\": \"{:.0%}\".format}))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "c78a9ba1",
   "metadata": {},
   "source": [
    "In this run, **67%** of the chunks land in a cluster that mostly holds their own chapter. Some chapters come out almost untouched, as a cluster of their own. The clusters at the bottom of the table are more interesting: there, k-means put chunks from several chapters together, because they're about the same thing. Look inside the cluster that mixes the most:"
   ]
  },
  {
   "cell_type": "code",
   "id": "2e414e94",
   "metadata": {},
   "source": [
    "mixed = overview.topic.iloc[-1]                                              # the cluster with the most mixed chapters\n",
    "print(mixed)\n",
    "inside = chunks[chunks.topic == mixed].groupby(\"chapter\").heading.agg(lambda headings: \" · \".join(sorted(set(headings))))\n",
    "HTML(inside.to_frame().to_html())"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "19bf6a7d",
   "metadata": {},
   "source": [
    "This one is hard to name. In this run, it puts the scores and thresholds of Model Evaluation together with entropy from Decision Trees, the label probabilities of Regression and much of Naive Bayes. Perhaps the model sees one topic in them, predicting a label and how sure you can be of it; perhaps k-means simply had a cluster left over. The clusters are always mathematically sound, but whether they're useful is up to you: [interpreting them is the real work](https://ai.kuleuven.be/aivooriedereen/en/clustering#geometric-not-meaningful).\n",
    "\n",
    "On the map, colored by cluster this time, you see where k-means cut across the chapters: an island in two colors, or one color spread over several islands."
   ]
  },
  {
   "cell_type": "code",
   "id": "b48ddf3d",
   "metadata": {},
   "source": [
    "draw_map(\"topic\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "56019218",
   "metadata": {},
   "source": [
    "**Try it.** Put the name of the chapter in front of every chunk as well: in the cell with `cut`, make it `f\"{section.chapter} > {section.heading}\\n{piece}\"`, and run the cells again from there. K-means then finds the chapters much better (about 90% instead of 70%), but not because it understands the course any better: every chunk now carries the answer. That's the mistake of a [data leak](https://ai.kuleuven.be/aivooriedereen/en/model-evaluation#data-leakage), where the answer sneaks into the data, and it's why the chunks in this notebook only get their heading.\n",
    "\n",
    "Here, the number of chapters was an obvious choice for *k*. For text without such a natural number, there's rarely one right *k*: it depends on how many topics you want to see (see [k remains a choice](https://ai.kuleuven.be/aivooriedereen/en/clustering#k-remains-a-choice))."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5dab194",
   "metadata": {},
   "source": [
    "## 🌲 A family tree of the chapters\n",
    "\n",
    "K-means needs *k* in advance. [Hierarchical clustering](https://ai.kuleuven.be/aivooriedereen/en/clustering#hierarchical-clustering) builds every grouping at once, from fine to coarse, and draws them as a **dendrogram**. On hundreds of chunks that tree gets unreadable, but on one average vector per chapter it becomes a family tree of the course:"
   ]
  },
  {
   "cell_type": "code",
   "id": "2e7e3a51",
   "metadata": {},
   "source": [
    "names = list(chunks.chapter.unique())                                     # in the order of the course\n",
    "averages = np.array([vectors[(chunks.chapter == name).to_numpy()].mean(axis=0) for name in names])\n",
    "tree = linkage(averages, method=\"average\", metric=\"cosine\")\n",
    "\n",
    "plt.figure(figsize=(8, 6))\n",
    "dendrogram(tree, labels=[name.split(\" \", 1)[1] for name in names], orientation=\"right\")   # without the emoji\n",
    "plt.xlabel(\"distance between the clusters (1 − cosine similarity)\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ae519ed1",
   "metadata": {},
   "source": [
    "Compare the tree with the menu on the left of the site. Many branches match: Search Algorithms, Heuristic Search and Game Trees (Reasoning), History and Dimensions (Introduction), and most of Machine Learning hangs together. Where the tree differs, it often has a point. Naive Bayes joins Probability and Bayesian Networks, because it's built on probabilities. Model Evaluation, at the very end of the menu, lands in the middle of Machine Learning: that's what it evaluates. Clustering stays apart from the rest of Machine Learning: it's the only chapter there that works without labels. Logic hangs on a long branch of its own: in this course, no other chapter looks much like it. And the search chapters join the rest only at the very top.\n",
    "\n",
    "Which chapter would you have put elsewhere?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d376b4f8",
   "metadata": {},
   "source": [
    "## 🔍 Searching on meaning\n",
    "\n",
    "A search engine on meaning takes only a few lines: turn the question into a vector, and take the chunks with the highest dot product. The best hit shows its whole chunk; click the others to read theirs. Type another question in the field and run the cell again; in Colab it runs by itself when you change the question."
   ]
  },
  {
   "cell_type": "code",
   "id": "bc68435b",
   "metadata": {},
   "source": [
    "def search(question, k=5):\n",
    "    # The k chunks that lie closest to the question, the best one first\n",
    "    scores = vectors @ model.encode(question, normalize_embeddings=True)\n",
    "    best = np.argsort(-scores)[:k]\n",
    "    return chunks.iloc[best].assign(score=scores[best])\n",
    "\n",
    "\n",
    "def show_results(results):\n",
    "    # The results with a link to every section: the best one open, a click opens the whole chunk of the others\n",
    "    rows = []\n",
    "    for rank, row in enumerate(results.itertuples()):\n",
    "        rows.append(f'<details{\" open\" if rank == 0 else \"\"}><summary style=\"cursor:pointer\">{row.score:.2f} '\n",
    "                    f'<a href=\"{row.url}\" target=\"_blank\">{html.escape(row.chapter)} › {html.escape(row.heading)}</a></summary>'\n",
    "                    f'<div style=\"white-space:pre-wrap;max-width:50em;margin:4px 0 8px 1.2em;font-size:smaller\">{html.escape(row.text)}</div></details>')\n",
    "    display(HTML(\"\".join(rows)))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "8cb209c7",
   "metadata": {},
   "source": [
    "question = \"Why did AI research run out of money in the 1970s?\"  # @param {type:\"string\"}\n",
    "show_results(search(question))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "5e4269bf",
   "metadata": {},
   "source": [
    "The question says *run out of money*; the course says that governments *cut their funding* and that the *funding dried up*. Different words, the same meaning, and so the first hit is the section about the first AI winter. A few more to try: \"Who first asked whether machines can think?\", \"How do I group my customers when nobody labeled them?\" or \"My model is perfect on the training data but bad on new data. Why?\".\n",
    "\n",
    "And in another language:"
   ]
  },
  {
   "cell_type": "code",
   "id": "10677ca8",
   "metadata": {},
   "source": [
    "show_results(search(\"Hoe kies ik hoeveel clusters ik nodig heb?\"))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "2e69d956",
   "metadata": {},
   "source": [
    "The question is in Dutch and the course in English, and still the search lands in the section about how many clusters to choose. The model puts a Dutch question and an English answer close together, as it did with the train sentences at the start.\n",
    "\n",
    "Two warnings, though. The scores lie close together, so a high score doesn't mean that a chunk answers the question: it only lies closer than the rest. And for names, numbers and exact terms, ordinary search on words often does better, so large search engines combine both."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f907656",
   "metadata": {},
   "source": [
    "## 🤖 Extra: a study assistant for this course\n",
    "\n",
    "A search engine plus a language model: those are the ingredients of [retrieval-augmented generation](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#retrieval-augmented-generation) (RAG). First look things up, then answer, with the sources. Here the language model gets the search engine as a [tool](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#tool-calling): it decides itself what to search for, and how often, before it answers. The [notebook about large language models](https://ai.kuleuven.be/aivooriedereen/en/notebook/large-language-models) explains tool calls step by step; here you only plug in your search engine.\n",
    "\n",
    "This part needs a free key from [OpenRouter](https://openrouter.ai), stored in Colab's 🔑 *Secrets* as `OPENROUTER_API_KEY`. Did you make one for that notebook? Then only switch on *Notebook access* for this one. If not, its [section about the key](https://ai.kuleuven.be/aivooriedereen/en/notebook/large-language-models#a-free-key) explains how to get one. As there: never put a key in the code, and send nothing private to a free model."
   ]
  },
  {
   "cell_type": "code",
   "id": "1cf10268",
   "metadata": {},
   "source": [
    "try:\n",
    "    from google.colab import userdata                     # in Colab: the key from the 🔑 Secrets\n",
    "    api_key = userdata.get(\"OPENROUTER_API_KEY\")\n",
    "except ImportError:                                         # elsewhere: an environment variable, or type it in\n",
    "    api_key = os.environ.get(\"OPENROUTER_API_KEY\") or getpass.getpass(\"Your OpenRouter key: \")\n",
    "\n",
    "client = OpenAI(base_url=\"https://openrouter.ai/api/v1\", api_key=api_key)\n",
    "\n",
    "# The free model we use, followed by the free models that OpenRouter tries when it's busy\n",
    "MODEL = \"nvidia/nemotron-3.5-super-vl:free\"\n",
    "MODELS = [MODEL, \"google/gemma-4-31b-it:free\", \"openrouter/free\"]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "213c80d2",
   "metadata": {},
   "source": [
    "The model sees the tool as a description in JSON: its name, what it does, and what it needs (a `query`). `ask_course` sends the question with that description. As long as the model asks for searches, it runs them with `search` and sends the chunks back; as soon as the model answers without searching, that's the answer. Under every search you see its results, as in your search engine above. The model gets the whole text of those five chunks, not only their headings, so click them open to read what it read."
   ]
  },
  {
   "cell_type": "code",
   "id": "2359da0a",
   "metadata": {},
   "source": [
    "SEARCH_TOOL = {\"type\": \"function\", \"function\": {\n",
    "    \"name\": \"search_course\",\n",
    "    \"description\": \"Searches the course AI voor Iedereen on meaning, and returns the 5 chunks that match best, with their links.\",\n",
    "    \"parameters\": {\"type\": \"object\", \"required\": [\"query\"], \"properties\": {\n",
    "        \"query\": {\"type\": \"string\", \"description\": \"What to look for: a few words or a question.\"}}},\n",
    "}}\n",
    "SYSTEM = \"\"\"You are a study assistant for the course AI voor Iedereen of KU Leuven.\n",
    "Before you answer, look up what the course says with search_course, as often as you need.\n",
    "Answer only with what the course says, in at most 150 words, and link every section you use as [heading](url), without its emoji.\n",
    "Write formulas and symbols as plain text, without LaTeX.\n",
    "If the course doesn't cover the question, say so.\n",
    "Answer in the language of the question: a question in English gets an answer in English.\"\"\"\n",
    "\n",
    "\n",
    "def ask_course(question):\n",
    "    # Lets the model search the course until it can answer; shows every search and the answer, returns the conversation\n",
    "    messages = [{\"role\": \"system\", \"content\": SYSTEM}, {\"role\": \"user\", \"content\": question}]\n",
    "    for step in range(6):\n",
    "        response = client.chat.completions.create(model=MODEL, messages=messages, tools=[SEARCH_TOOL],\n",
    "                                                  extra_body={\"models\": MODELS})\n",
    "        message = response.choices[0].message\n",
    "        messages.append(message.model_dump(exclude_none=True))\n",
    "        if not message.tool_calls:                                   # no search: this is the answer\n",
    "            print(\"Answered by\", response.model)\n",
    "            display(HTML(markdown.markdown(message.content or \"\", extensions=[\"tables\"])))\n",
    "            return messages\n",
    "        for call in message.tool_calls:\n",
    "            query = json.loads(call.function.arguments).get(\"query\", question)\n",
    "            found = search(query)\n",
    "            print(\"🔍\", query)\n",
    "            show_results(found)\n",
    "            results = found[[\"chapter\", \"heading\", \"url\", \"text\"]].to_dict(\"records\")\n",
    "            # ensure_ascii=False: 🔢 and ï stay as they are, instead of codes such as 🔢 that the model has to decode\n",
    "            messages.append({\"role\": \"tool\", \"tool_call_id\": call.id, \"content\": json.dumps(results, ensure_ascii=False)})\n",
    "    return messages"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "8606c83b",
   "metadata": {},
   "source": [
    "conversation = ask_course(\"How do I choose the number of clusters in k-means?\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "5ed9120f",
   "metadata": {},
   "source": [
    "The model wrote its own search query, read the chunks that came back, and answered with links to the sections it used. Those chunks are all it saw of the course, so open them and compare: does the text really say what the answer claims? Which model answered depends on how busy the free models are, and the answer differs a little every time.\n",
    "\n",
    "A question about two chapters at once:"
   ]
  },
  {
   "cell_type": "code",
   "id": "4f74965c",
   "metadata": {},
   "source": [
    "conversation = ask_course(\"What's the difference between the k in k-means and the k in k-nearest neighbors?\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "3589f972",
   "metadata": {},
   "source": [
    "Count the searches: plain RAG searches once, with the question itself. Here the model decides what it still needs to know, so for a question about two chapters it can search more than once, for instance once per chapter. You've just built a small version of [Gemini Notebook](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#retrieval-augmented-generation) from the chapter, on the course you're taking.\n",
    "\n",
    "Your turn: ask about anything in the course, in English or in Dutch. And keep comparing: an answer with sources is more trustworthy, but it isn't guaranteed to be right (see [hallucinations](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#hallucinations)). When we ran this cell, the answer ended with \"The course notes that both techniques using the letter k is pure coincidence\". The chunk it links to does say that, but about the k of k-fold cross-validation and the k of nearest neighbors, not about k-means."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5679331e",
   "metadata": {},
   "source": [
    "## 🧰 Embeddings for your own documents\n",
    "\n",
    "The recipe for your own texts:\n",
    "\n",
    "1. **Collect the text with its structure**: headings, page numbers, one message or review per row. For PDF, Word and PowerPoint files, [MarkItDown](https://github.com/microsoft/markitdown) turns them into text with their headings.\n",
    "2. **Cut at that structure**: one chunk per section or paragraph, well below what the model reads (512 tokens here), with its heading in front.\n",
    "3. **Choose a model** for your language. This granite model is small and fast; [multilingual-e5-small](https://huggingface.co/intfloat/multilingual-e5-small) knows a hundred languages, but needs `\"query: \"` in front of questions and `\"passage: \"` in front of the texts. Bigger models find a bit more, but without a graphics card they take minutes instead of seconds.\n",
    "4. **Embed once, and save**: `np.save(\"vectors.npy\", vectors)`, and `np.load` the next time. Up to a hundred thousand chunks, `vectors @ question` is fast enough; beyond that, a vector database such as FAISS or Chroma searches faster.\n",
    "5. **Test the search** with ten questions whose answer you know, before you trust it.\n",
    "6. **For clusters**: choose *k* yourself, read the chunks closest to every center to name the clusters, and look for odd clusters: those are often duplicates or junk in your data."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4453fea8",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "*By [Thomas Winters](https://thomaswinters.be) for [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en), KU Leuven. The latest version of this notebook: [ai.kuleuven.be/aivooriedereen/en/notebook/embeddings](https://ai.kuleuven.be/aivooriedereen/en/notebook/embeddings).*"
   ]
  }
 ],
 "metadata": {
  "aivi": {
   "chapters": [
    "embeddings"
   ],
   "language": "en",
   "title": "Embeddings in Python",
   "requires_env": [
    "OPENROUTER_API_KEY"
   ]
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
