How does AI search find text that means the same thing?

A word search misses a reworded question. Give each text a list of numbers and rank by the angle between lists: the closest texts mean the same.

  • 8 min read
  • 17 min to go deeper
On this page
  1. In one minute
  2. Explore the numbers
  3. How it works
  4. Your turn
  5. What this means when you build
  6. Go deeperoptional
  7. Skills this lesson builds
  8. Check yourself
  9. Further reading
  10. Codeoptional

A help page has nine short answers. A customer asks “Can I get my money back?” The answer is “Cancel within five days and we repay you in full.”, but it shares no word with the question, and 8 of the 9 sentences share none. A search that matches words puts “Get back to the login page and sign in again.” first, because it shares “get” and “back”. A search by meaning puts the repay sentence first, with a closeness of 1.000. The trick is to turn every text into a short list of numbers, so that texts about the same thing get lists that point the same way, and then to find the stored lists closest to the question’s list. In a toy with four numbers per text you will see it work, and see where it fails: a code such as E4410 has no meaning to match, and a speed-up that looks in fewer places can miss the best answer.

In one minute

Think of a map of the topics in a help centre. Money is one direction, accounts another, delivery a third, opening hours a fourth. Every sentence is an arrow from the middle of the map, pointing toward the topics it talks about. A sentence about refunds points straight along “money”. A sentence about a card points along money with a small lean toward accounts. A customer’s question gets an arrow the same way.

To search, you do not compare words. You compare where the arrows point. Two arrows that point the same way score 1, however long they are, and two that have nothing in common score 0. The answer is the stored sentence whose arrow points most nearly the way the question’s does. “Money back” and “repay” are different words, but they point the same way, so they match.

A word search is like the index at the back of a book: it finds a word only when that exact word is there. That makes it the right tool for an order number and the wrong tool for a reworded question. The map has a gap of its own. Something with no direction on the map, such as an error code, does not point anywhere, so pointing cannot find it. Good search uses both. A real system learns its map from a huge pile of text and has hundreds of directions with no names. The map here has four, named and set by hand, so you can follow every number.

Explore the numbers

Open the widget. It opens on “Can I get my money back?” searched by words only. Each row is one of the nine sentences. A longer bar is a better match, and the text on the right says why. Press Meaning and the rows reorder: the repay sentence comes first. Then try the other questions. “Where is my order?” shares no word with any sentence, yet meaning finds the parcel sentence. “Code E4410” does the opposite: meaning has nothing to rank, and words find the error sentence. Meaning, one cell is the speed-up from step 5 of How it works. Press it on “Can I pay for delivery?” and see which sentences it never looks at. Open More settings to see the question as a list of numbers. Every number is picked by hand to show the mechanism; a real system learns its numbers.

How it works

The picture, step by step

The help-centre map, one step at a time. The next part shows the line of code behind each step, and the part after that runs the steps on real sentences.

The question “Can I pay for delivery?” is an arrow leaning between the money axis and the delivery axis. The pay-extra sentence is a close arrow with cosine 0.962. The parcel sentence lies along the delivery axis with cosine 0.743, and the repay sentence along the money axis with cosine 0.669.

Figure 1. The question and three stored sentences, drawn in two of the four topics. The green arrow is the closest to the question. The number beside each sentence is its closeness to the question.

  1. Give each word a few numbers. The toy has four directions: money, account, delivery and hours. Each word it knows gets one number per direction, for how much it points that way. “refund” is all money: (1, 0, 0, 0). “card” is mostly money with a little account: (0.8, 0.1, 0, 0). A word the toy has no numbers for, like “E4410”, points nowhere. (A real system learns its directions and numbers from a huge amount of text. Here they are set by hand.)
  2. Give each text one arrow. Add up the numbers of its words, direction by direction, then scale the result so the arrow has length 1. Scaling keeps a long text from winning just for being long. The question gets its arrow the same way. (Engineers call this list of numbers an embedding.)
  3. Measure the angle between two arrows. Multiply the matching numbers of the two lists and add them up, which is called the dot product, then divide by the two lengths. The answer is 1 for arrows that point the same way and 0 for arrows with nothing in common. It is called the cosine, because it is the cosine of the angle between the arrows. When both arrows have length 1, nothing is left to divide by, and the dot product alone is the score.
  4. Score every stored text and keep the best. The stored arrows are made once, ahead of time. For each question, score the question’s arrow against every stored arrow, sort from best to worst and keep the top few. This is called nearest-neighbour search: the nearest stored arrow is the best match.
  5. For a huge store, look in fewer places. Scoring everything costs the number of texts times the numbers in each list, for every question. So big systems sort the arrows into groups, called cells, ahead of time, and score only the cells nearest the question. That is faster, and sometimes it misses the true best.

Each step in code

One real line of the lesson’s code does each step. The files are in code/, and the line numbers are those of this lesson’s files.

Step The code line What it does
1. Numbers for a word embed_search.py:15
"refund": (1.0, 0.0, 0.0, 0.0),
The table WORD_VECTORS holds one list of four numbers per word, in the order of TOPICS (money, account, delivery, hours). A word missing from the table is skipped in step 2, by the .get(w, ()) on line 109.
2. One arrow per text embed_search.py:112
return tuple(x / size for x in total) if size else tuple(total)
Line 110 adds each known word’s list into total, and line 111 sets size to the length of total. This line divides every number by size, so the new length is 1. If no word is known, size is 0 and the list stays all zeros.
3. The angle embed_search.py:102
return dot(a, b) / (length(a) * length(b))
dot multiplies matching numbers and adds them. length is the square root of the sum of the squares. Lines 100 and 101 return 0.0 for an all-zero list, which would otherwise divide by zero.
4. Score all, keep the best embed_search.py:118
return sorted(scored, key=lambda pair: (-pair[1], pair[0]))[:k]
scored (line 117) holds (index, cosine) for every stored list. This line sorts the best first, and on a tie the earlier sentence first, then keeps the first k.
5. Look in fewer places embed_search.py:145
order = sorted(range(len(query_vector)), key=lambda c: (-query_vector[c], c))[:probes]
In the toy a cell is a topic: a stored list belongs to the topic where its largest number sits (cell_of, lines 135 to 137). This line picks the probes topics the question leans on most. Line 146 collects the sentences in those cells, and cell_search (line 149) scores only those.

A real run

show_numbers.py runs the steps on the nine sentences. It calls the same functions as the table and only prints what they return. Run it from the lesson’s folder:

cd code && uv run --no-project python show_numbers.py
1. Words only. Question: "Can I get my money back?"
   content words: get, money, back
   2 shared  Get back to the login page and sign in again.  (get, back)
   0 shared  Cancel within five days and we repay you in full.  (none)
   0 shared  A refund reaches your card in five days.  (none)
   sentences sharing no word with the question: 8 of 9

2. Meaning. Same question, closest 4 sentences (cosine):
   1.000  Cancel within five days and we repay you in full.
   0.998  A refund reaches your card in five days.
   0.970  Error E4410 means your payment failed.
   0.835  Pay extra for fast delivery with your card.

3. One comparison by hand: the question and the refund sentence
   topics: money, account, delivery, hours
   question words the toy knows: money -> (1.000, 0.000, 0.000, 0.000)
   sentence words the toy knows: refund, card -> (0.998, 0.055, 0.000, 0.000)
   sentence before scaling: (1.800, 0.100, 0.000, 0.000) length 1.803
   dot = 0.998, lengths = 1.0 and 1.0, cosine = 0.998

4. Length does not change the cosine
   dot = 5.0, cosine = 1.0
   sharing nothing: cosine = 0.0

5. Every question: best sentence by words, best by meaning
   Can I get my money back?
      words   2 shared: Get back to the login page and sign in again.
      meaning 1.000: Cancel within five days and we repay you in full.
   I lost my password
      words   1 shared: Forgot your password? We can send a new one.
      meaning 0.998: Get back to the login page and sign in again.
   When are you open?
      words   1 shared: The shop is open from nine to five.
      meaning 1.000: Opening times are nine to five on weekdays.
   Where is my order?
      words   no shared word
      meaning 0.976: Your parcel ships within two days.
   Code E4410
      words   1 shared: Error E4410 means your payment failed.
      meaning 0.000, nothing to rank
   Can I pay for delivery?
      words   2 shared: Pay extra for fast delivery with your card.
      meaning 0.962: Pay extra for fast delivery with your card.

6. A question with no word the toy knows
   vector: (0.000, 0.000, 0.000, 0.000)  cosines: [0.0]

7. How many multiplications one question costs (documents x list length)
           9 x   4 =          36
       1,000 x 768 =     768,000
   1,000,000 x 768 = 768,000,000

8. Looking only in the closest cell(s). Question: Can I pay for delivery?
   all 9: best is Pay extra for fast delivery with your card. at 0.962
   1 cell : compared 1, best is Your parcel ships within two days. at 0.743
   2 cells: compared 5, best is Pay extra for fast delivery with your card. at 0.962

Read it against the five steps.

  • Steps 1 and 2, the question. “money” is the only word of the question the toy has numbers for, so the question’s list is (1.000, 0.000, 0.000, 0.000): all money. “get” and “back” have no numbers, but the word search in section 1 counts them anyway.
  • Steps 2 and 3, by hand. The refund sentence has two known words, “refund” and “card”, which add up to (1.800, 0.100, 0.000, 0.000), a list of length 1.803. Dividing by 1.803 gives (0.998, 0.055, 0.000, 0.000), a list of length 1. The dot product with the question’s list is 1.000 x 0.998 + 0.000 x 0.055, which is 0.998. Both lengths are 1, so the cosine is 0.998 too.
  • Words against meaning. In section 1 the content words of the question are get, money and back. Only the login sentence has any of them, 2 shared, so it ranks first. The other 8 sentences share nothing, including the one that answers. In section 2 the repay sentence comes first with 1.000, because “repay” and “money” have the same list, then the refund sentence with 0.998. Figure 2 shows both searches as bars.
  • Close is not the same as correct. Third by meaning, at 0.970, is “Error E4410 means your payment failed.” It is about money, so it points nearly the way the question does, but it does not answer it. A score says how alike two arrows are, not whether a text answers the question.
  • Length (section 4). The list (1, 0, 0, 0) and the same list five times as long, (5, 0, 0, 0), have a dot product of 5.0 and a cosine of 1.0. The dot product grows with length and the cosine does not. Lists that share no direction score 0.0.
  • The six questions (section 5). Each search finds a sensible sentence for some questions and misses for others. For “When are you open?”, words find the shop sentence through “open” and meaning finds the opening-times sentence at 1.000. That sentence says “Opening”, and this word search does not cut “Opening” back to “open”. Both are sensible. “Where is my order?” shares no word with any sentence, and meaning finds the parcel sentence at 0.976. For “I lost my password”, words find the forgot-password sentence and meaning finds the login sentence, which shares no word with the question. Both are sensible.
  • The unknown code (section 6). “Code E4410” has no word the toy has numbers for, so its list is all zeros, and the only cosine any sentence gets is 0.0. Meaning cannot choose between the nine sentences, while the word search in section 5 finds the error sentence.
  • The cost (section 7). With stored lists of length 1, a score is a dot product: one multiplication per number. Comparing the question with 9 sentences of 4 numbers is 9 x 4 = 36 multiplications. For 1,000 texts of 768 numbers it is 768,000, and for 1,000,000 texts it is 768,000,000, for every question.
  • The speed-up (section 8). The question “Can I pay for delivery?” leans more toward delivery than toward money (Figure 1), so one cell means looking only in the delivery cell. It holds 1 sentence, the parcel one, at 0.743, while the best of all 9 scores 0.962. Two cells compare 5 sentences and find the best again. That is the trade: fewer comparisons, and sometimes the best is missed.

For the question “Can I get my money back?”, two columns of bars over the nine sentences. By shared words, only the login sentence has a bar, with 2 shared words. By cosine, the repay sentence is longest at 1.000, then the refund sentence at 0.998 and the payment error sentence at 0.970.

Figure 2. Sections 1 and 2 of the run as bars, one row per sentence. Green marks the top match of each search.

The sentences, scores and lists are a toy. A real system makes hundreds of numbers per text, and learns them instead of having them picked by hand.

Hands on

Your turn

The toy has no numbers for “cash”, so a question that uses it gets an all-zero list. Teach it the word.

  1. In code/embed_search.py, add the line "cash": (1.0, 0.0, 0.0, 0.0), inside WORD_VECTORS, next to the other money words.
  2. From the code folder run uv run --no-project python embed_search.py "Can I get my cash back?" before and after the change.

Look at the three scores before the change. Then look at which sentences come first after it, and at whether the third one answers the question.

What you should see

Before the change:

question: Can I get my cash back?
  0.000  Cancel within five days and we repay you in full.
  0.000  A refund reaches your card in five days.
  0.000  Forgot your password? We can send a new one.

After the change:

question: Can I get my cash back?
  1.000  Cancel within five days and we repay you in full.
  0.998  A refund reaches your card in five days.
  0.970  Error E4410 means your payment failed.

Before, no word of the question had numbers, so all nine cosines were 0.0 and the first three sentences came out in list order. After, “cash” has the same list as “money”, so the question gets the same top three as “Can I get my money back?” in the run above. The third is the error message again: close in meaning, not an answer.

What this means when you build

  • Use both searches. Meaning finds a reworded question and words find an exact string. In the toy, “Where is my order?” is found only by meaning, and “Code E4410” only by words. Real systems often run both and merge the two rankings, which is called hybrid search.
  • Make questions and texts the same way. Two lists can be compared only if the same embedding model made both, with the same count of numbers. The fourth number of one model means nothing next to the fourth of another. When you change models, make every stored list again.
  • Read a score as “alike”, not “right”. The third hit for the money question scores 0.970 and is an error message. Choose how many results to keep, and a cutoff, by trying real questions, as in How do I check my AI’s answers with a small test set?. Do not copy a cutoff from another system: scores from different models are on different scales.
  • Embed short passages, not whole pages. One list for a long page is a blend of all its topics, like the arrow of the “Pay extra” sentence in Figure 1, which points between money and delivery. A question about one topic then points only part of the way toward it. Split long documents into short passages first.
  • Count the scan. Brute force costs texts times numbers per list for every question: 768,000 multiplications for 1,000 texts and 768,000,000 for 1,000,000. The first needs no shortcut. The second is where approximate search pays off. Storing the lists also takes memory in proportion.
  • Measure what the shortcut misses. A speed-up can skip the best text, as one cell does for “Can I pay for delivery?”: the parcel sentence at 0.743 instead of the best at 0.962. Run the full scan on real questions, count how often the shortcut returns the same top result, and search more cells until that is high enough.

Optionalabout 17 min

Go deeper

Optional. This part is for readers who write Python. The code is in the code/ folder next to this lesson. From inside that folder, uv run --no-project python show_numbers.py prints the numbers above, and uv run --no-project --with pytest python -m pytest -q -p no:cacheprovider runs the tests (the widget tests also need Node.js). The scripts run on plain python3 too.

The formula

cosine(a, b) = (a1 x b1 + a2 x b2 + ...) / (length(a) x length(b))
length(a)    = square root of (a1 x a1 + a2 x a2 + ...)

Draw two lists as arrows from the same point. Their dot product equals length(a) times length(b) times the cosine of the angle between them, so dividing by the two lengths leaves the cosine. When every number is 0 or more, as in the toy, the score runs from 0 to 1. Real lists can point apart and score below 0.

If both lists have length 1, the cosine is the dot product, and the squared straight-line distance between them is 2 minus 2 times the cosine. So the closest list by distance is also the best by cosine, which is why a search can be described either way. embed scales every list to length 1 for this reason: it makes the score cheap.

The code

The word search is a set of shared words after dropping filler words:

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


def content_words(text):
    return [w for w in words(text) if w not in STOP_WORDS]


def shared_words(query, doc):
    """The content words that the question and the document have in common, in the question's order."""
    doc_words = set(content_words(doc))
    seen = []
    for w in content_words(query):
        if w in doc_words and w not in seen:
            seen.append(w)
    return seen

words lowercases and splits on anything that is not a letter or digit, which is why “E4410” is one word. It never cuts “Opening” back to “open”.

The text-to-list step adds the lists of the known words and scales the sum to length 1:

def embed(text):
    """Add up the lists of the words the toy knows, then scale the result to length 1."""
    total = [0.0] * len(TOPICS)
    for w in words(text):
        for i, x in enumerate(WORD_VECTORS.get(w, ())):
            total[i] += x
    size = length(total)
    return tuple(x / size for x in total) if size else tuple(total)

WORD_VECTORS.get(w, ()) returns an empty tuple for an unknown word, so the inner loop adds nothing. If no word is known, size is 0, and the all-zero list comes back unscaled instead of dividing by zero.

The score and the ranking:

def length(v):
    return math.sqrt(sum(x * x for x in v))


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def cosine(a, b):
    """1 when two lists point the same way, 0 when they share nothing, whatever their lengths."""
    if length(a) == 0 or length(b) == 0:
        return 0.0
    return dot(a, b) / (length(a) * length(b))
def nearest(query_vector, vectors, k):
    """Score every stored vector against the question and keep the k best: (index, cosine), best first."""
    scored = [(i, cosine(query_vector, v)) for i, v in enumerate(vectors)]
    return sorted(scored, key=lambda pair: (-pair[1], pair[0]))[:k]

cosine divides by both lengths so it works on any two lists. For stored lists that are already length 1, a real system skips the division and the square roots and computes only the dot product. The toy keeps the division so the same function can compare the lists of length 5 and 1 in section 4 of the run.

The cell shortcut:

def cell_of(v):
    """A toy cell: the topic where the list is largest."""
    return max(range(len(v)), key=lambda i: v[i])


def cells_checked(query_vector, vectors, probes):
    """The indexes in the `probes` cells whose topic the question leans on most, cell by cell."""
    cells = {}
    for i, v in enumerate(vectors):
        cells.setdefault(cell_of(v), []).append(i)
    order = sorted(range(len(query_vector)), key=lambda c: (-query_vector[c], c))[:probes]
    return [i for c in order for i in cells.get(c, [])]


def cell_search(query_vector, vectors, probes):
    """Compare the question only with the vectors in those cells. Returns (best index, how many were compared)."""
    scanned = cells_checked(query_vector, vectors, probes)
    best = max(scanned, key=lambda i: (cosine(query_vector, vectors[i]), -i)) if scanned else None
    return best, len(scanned)

probes is how many cells to search. In section 8 of the run, 1 probe compares 1 sentence and 2 probes compare 5. Searching all four cells is the full scan, which a test checks.

What the code costs

Each stored list needs one multiplication per number to score against the question, so a full scan costs texts times numbers: 9 x 4 = 36 for the toy, 768,000 for 1,000 texts of 768 numbers, and 768,000,000 for 1,000,000. The cost grows in step with the store, and with the length of each list.

A cell search pays for the cells it looks in. The toy builds its cells inside cells_checked on every call, to stay short. A real system builds them once, when it stores the lists, by grouping lists that lie close together, and keeps a short list of cell centres to find the nearest cells to a question. Some systems use a different shortcut, linking each list to its near neighbours and walking from list to list toward the question. Both give up the guarantee of the full scan for speed, and the number of cells or steps is the knob.

What the toy leaves out, in detail

  • The numbers are picked by hand. A real embedding model learns its numbers from text, and it reads the whole text, so a word can get different numbers in two sentences (“bank” of a river and a bank account) and word order matters. The toy only adds up fixed word lists, so “refund card” and “card refund” give the same list.
  • Four named directions. A real list has hundreds of numbers, and no single one means “money”. Only the angle between whole lists carries meaning.
  • An unknown word is a cliff. In the toy it adds nothing. A real model cuts text into pieces first (see What is a token, and why is AI priced per token?), so it always gives some list, but codes and rare names are usually where it is weakest, and where word search is strongest.
  • The word search is simpler than a real one. It has no stemming, so “open” does not match “Opening”, and it counts every shared word equally. Real word search can cut words back to a stem and give rare words more weight. It still cannot connect “money” to “repay”.
  • Scores have no common scale. 0.970 means “alike for this toy”. The same number from another model means something else.
  • A different meaning of the word. The token table inside a model is also called its embeddings, and it is a different thing from the list of numbers for a whole text.
  • Stored lists are made once. rank_meaning makes the stored lists again on every call, to keep the code short.

Proof it works

test_embed_search.py pins the toy to the lesson. One table holds the six questions of section 5: for each, the sentence a word search puts first with its count of shared words, and the sentence meaning puts first with its cosine. Other tests check that a cosine ignores length, that every known sentence gets a list of length 1, that the squared distance between two lists of length 1 equals 2 minus 2 times their cosine, that a sum ignores word order, that “Code E4410” gets an all-zero list, and that one cell compares 1 sentence and misses the best while two cells compare 5 and find it. Four more tests read this page. The output block in A real run must equal what show_numbers.py prints, and each line number cited in the table and in the text must point at the line it names. Each Python block above must appear word for word in embed_search.py. The two outputs in Your turn must equal what the script prints before and after the edit, which the test makes on a copy. The figures must equal what make_figs.py draws, with every decimal of their alt text drawn in them.

test_widget.py checks the page. A script that runs the widget’s own JavaScript in Node must agree with the Python toy to 1e-12 on every list and score, and exactly on every order and list of shared words. A second script presses every question in every mode and compares what the page shows with the toy’s ranking.

You can also check one number with a calculator. Section 3 of the run shows the refund sentence before scaling, (1.800, 0.100, 0.000, 0.000). Its length is the square root of 1.800 x 1.800 + 0.100 x 0.100, which is 1.803, and 1.800 divided by 1.803 is 0.998.

Where this is used in practice

Meaning search is the lookup step behind a chatbot that answers from your own documents: the question is turned into a list, the closest stored passages are found, and they are placed in the prompt so the model can answer from them. It also finds duplicate support tickets, similar products and related articles. Published work covers each step of this lesson: how lists for words are learned from text, how passages for question answering are found with lists instead of words, and how approximate indexes keep the search fast on very large stores. The papers are in Further reading.

Skills this lesson builds

  • Explain why a search on words misses a reworded question and a search on meaning does not.
  • Say what an embedding is, and work out the cosine of two short lists by hand.
  • Explain why lists are scaled to length 1 and what the cosine ignores.
  • Write nearest-neighbour search in plain Python and count its cost: texts times numbers per list.
  • Say what an approximate search gives up, and when to keep a word search beside meaning search.

Portfolio project: take a small set of short help sentences from a product you know, and a handful of questions that reword them. Pick four to six topics and give numbers to the words you need. Build both searches, and for each question report the best sentence by words and by meaning, and whether each is right. Add a few questions with codes or names and show which search finds them. Publish the table and a note on what you would change to use a real embedding model.

Check yourself

  1. In your own words, why does a word search not find “Cancel within five days and we repay you in full.” for “Can I get my money back?”, and how does meaning search find it?
    Answer The two share no word. The toy gives “money” and “repay” the same list, (1, 0, 0, 0), so the arrows point the same way and the cosine is 1.000. The word search puts the login sentence first instead, because it shares “get” and “back”.
  2. A text’s list before scaling is (1.800, 0.100, 0.000, 0.000). What is its length, and what does scaling give?
    Answer The length is the square root of 1.800 x 1.800 + 0.100 x 0.100, which is 1.803. Dividing each number by it gives (0.998, 0.055, 0.000, 0.000), a list of length 1.
  3. A list (1, 0, 0, 0) is compared with (5, 0, 0, 0). What are the dot product and the cosine, and which one would rank a long text above a short one for no good reason?
    Answer The dot product is 5.0 and the cosine is 1.0. The dot product grows with length, so it would favour a long text. The cosine divides the length out, and scaling every list to length 1 does the same.
  4. “Code E4410” gets 0.000 from every sentence by meaning. Why, and what finds the right sentence?
    Answer The toy has numbers for no word of it, so its list is all zeros and every cosine is 0.0. A word search finds the sentence “Error E4410 means your payment failed.” because it shares E4410. That is why a system keeps both searches.
  5. A store has 1,000,000 texts with 768 numbers each. How many multiplications does one full scan take, and how many for 1,000 texts? What does the one-cell shortcut give up in the toy?
    Answer 1,000,000 x 768 is 768,000,000, and 1,000 x 768 is 768,000. In the toy, one cell compares 1 of 9 sentences and returns the parcel sentence at 0.743, missing the best one at 0.962. Two cells compare 5 sentences and find it again.

Further reading

Web pages were read on 2026-12-02; they change.

Gentle

Deep

Optional

Code

Each file runs on its own. Download it, or read it here. The code is copyright 2026 spicysharkco, all rights reserved. You may run and change it on your own computer or account to follow the lesson. The Terms cover the rest, and quoted code from other projects keeps its own license.

embed_search.py172 linesDownload embed_search.py
Show code
"""A toy that finds text that means the same thing. Standard library only.

Every number about a word is picked by hand for the lesson. A real embedding model learns
many more numbers per text from lots of writing; the steps after that are the ones here.
"""
import math
import re
import sys

TOPICS = ("money", "account", "delivery", "hours")

# What each word is about, one number per topic. A word that is not here carries no topic.
WORD_VECTORS = {
    "repay": (1.0, 0.0, 0.0, 0.0),
    "refund": (1.0, 0.0, 0.0, 0.0),
    "money": (1.0, 0.0, 0.0, 0.0),
    "paid": (0.9, 0.0, 0.0, 0.0),
    "pay": (0.9, 0.0, 0.0, 0.0),
    "payment": (1.0, 0.0, 0.0, 0.0),
    "card": (0.8, 0.1, 0.0, 0.0),
    "extra": (0.3, 0.0, 0.0, 0.0),
    "failed": (0.4, 0.2, 0.0, 0.0),
    "error": (0.2, 0.2, 0.0, 0.0),
    "password": (0.0, 1.0, 0.0, 0.0),
    "login": (0.0, 1.0, 0.0, 0.0),
    "forgot": (0.0, 0.5, 0.0, 0.0),
    "lost": (0.1, 0.4, 0.0, 0.0),
    "sign": (0.0, 0.6, 0.0, 0.0),
    "page": (0.1, 0.2, 0.1, 0.0),
    "parcel": (0.0, 0.0, 1.0, 0.0),
    "ships": (0.0, 0.0, 0.9, 0.0),
    "delivery": (0.0, 0.0, 1.0, 0.0),
    "order": (0.2, 0.0, 0.9, 0.0),
    "fast": (0.0, 0.0, 0.3, 0.2),
    "open": (0.0, 0.0, 0.0, 1.0),
    "opening": (0.0, 0.0, 0.0, 1.0),
    "times": (0.0, 0.0, 0.0, 0.6),
    "weekdays": (0.0, 0.0, 0.0, 0.7),
    "shop": (0.2, 0.0, 0.1, 0.3),
}

# Short filler words that keyword search skips.
STOP_WORDS = {"a", "an", "and", "are", "can", "do", "for", "from", "how", "i", "in", "is", "it", "means",
              "my", "of", "on", "the", "to", "we", "when", "where", "with", "you", "your"}

DOCS = [
    "Cancel within five days and we repay you in full.",
    "A refund reaches your card in five days.",
    "Forgot your password? We can send a new one.",
    "Get back to the login page and sign in again.",
    "Your parcel ships within two days.",
    "The shop is open from nine to five.",
    "Opening times are nine to five on weekdays.",
    "Pay extra for fast delivery with your card.",
    "Error E4410 means your payment failed.",
]

QUERIES = [
    "Can I get my money back?",
    "I lost my password",
    "When are you open?",
    "Where is my order?",
    "Code E4410",
    "Can I pay for delivery?",
]


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


def content_words(text):
    return [w for w in words(text) if w not in STOP_WORDS]


def shared_words(query, doc):
    """The content words that the question and the document have in common, in the question's order."""
    doc_words = set(content_words(doc))
    seen = []
    for w in content_words(query):
        if w in doc_words and w not in seen:
            seen.append(w)
    return seen


def keyword_score(query, doc):
    return len(shared_words(query, doc))


def length(v):
    return math.sqrt(sum(x * x for x in v))


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def cosine(a, b):
    """1 when two lists point the same way, 0 when they share nothing, whatever their lengths."""
    if length(a) == 0 or length(b) == 0:
        return 0.0
    return dot(a, b) / (length(a) * length(b))


def embed(text):
    """Add up the lists of the words the toy knows, then scale the result to length 1."""
    total = [0.0] * len(TOPICS)
    for w in words(text):
        for i, x in enumerate(WORD_VECTORS.get(w, ())):
            total[i] += x
    size = length(total)
    return tuple(x / size for x in total) if size else tuple(total)


def nearest(query_vector, vectors, k):
    """Score every stored vector against the question and keep the k best: (index, cosine), best first."""
    scored = [(i, cosine(query_vector, v)) for i, v in enumerate(vectors)]
    return sorted(scored, key=lambda pair: (-pair[1], pair[0]))[:k]


def rank_keywords(query, docs=DOCS):
    scored = [(i, keyword_score(query, d)) for i, d in enumerate(docs)]
    return sorted(scored, key=lambda pair: (-pair[1], pair[0]))


def rank_meaning(query, docs=DOCS):
    return nearest(embed(query), [embed(d) for d in docs], len(docs))


def scan_cost(n_docs, dims):
    """Multiplications to compare one question with every stored vector of length 1."""
    return n_docs * dims


def cell_of(v):
    """A toy cell: the topic where the list is largest."""
    return max(range(len(v)), key=lambda i: v[i])


def cells_checked(query_vector, vectors, probes):
    """The indexes in the `probes` cells whose topic the question leans on most, cell by cell."""
    cells = {}
    for i, v in enumerate(vectors):
        cells.setdefault(cell_of(v), []).append(i)
    order = sorted(range(len(query_vector)), key=lambda c: (-query_vector[c], c))[:probes]
    return [i for c in order for i in cells.get(c, [])]


def cell_search(query_vector, vectors, probes):
    """Compare the question only with the vectors in those cells. Returns (best index, how many were compared)."""
    scanned = cells_checked(query_vector, vectors, probes)
    best = max(scanned, key=lambda i: (cosine(query_vector, vectors[i]), -i)) if scanned else None
    return best, len(scanned)


def config():
    """Everything ../widget.html needs, so its page script can run the same steps."""
    return {
        "topics": list(TOPICS),
        "docs": DOCS,
        "queries": QUERIES,
        "words": {w: list(v) for w, v in WORD_VECTORS.items()},
        "stop": sorted(STOP_WORDS),
        "opening": {"query": 0, "mode": "words"},
    }


if __name__ == "__main__":
    q = sys.argv[1] if len(sys.argv) > 1 else QUERIES[0]
    print("question:", q)
    for i, score in rank_meaning(q)[:3]:
        print(f"  {score:.3f}  {DOCS[i]}")
embed_widget.py29 linesDownload embed_widget.py
Show code
"""Keep the copy of the toy's numbers inside ../widget.html equal to the ones in embed_search.py.

    python3 embed_widget.py          rewrite the data block in widget.html
    python3 embed_widget.py --check  exit 1 if widget.html differs (test_widget.py runs the same check)
"""
import json
import re
import sys
from pathlib import Path

import embed_search as es

WIDGET = Path(__file__).resolve().parent.parent / "widget.html"
CONFIG_BLOCK = re.compile(r'(<script type="application/json" id="srch-config">)(.*?)(</script>)', re.S)


def embed(html):
    """html with the data block rewritten from embed_search.py."""
    settings = json.dumps(es.config(), ensure_ascii=False, separators=(", ", ": "))
    return CONFIG_BLOCK.sub(lambda m: m.group(1) + "\n" + settings + "\n" + m.group(3), html, count=1)


if __name__ == "__main__":
    current = WIDGET.read_text(encoding="utf-8")
    updated = embed(current)
    if "--check" in sys.argv:
        sys.exit(0 if updated == current else 1)
    WIDGET.write_text(updated, encoding="utf-8")
    print("widget.html data block now matches embed_search.py")
make_figs.py99 linesDownload make_figs.py
Show code
"""Draw ../figs/angle.svg and ../figs/ranking.svg from the numbers embed_search.py computes.

    uv run --no-project python make_figs.py          rewrite both figures
    uv run --no-project python make_figs.py --check  exit 1 if a figure differs from what the code draws
"""
import math
import sys
from pathlib import Path

import embed_search as es

FIGS = Path(__file__).resolve().parent.parent / "figs"
INK, GREY, ORANGE, GREEN = "#0a1626", "#44566b", "#b36200", "#00855F"
OPEN = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" width="{w}" height="{h}" role="img" font-family="system-ui, sans-serif" font-size="22" fill="{grey}">'

QUESTION = es.QUERIES[-1]                         # "Can I pay for delivery?" lies in the money and delivery topics only
SHOWN = {0: "repay sentence", 7: "pay-extra sentence", 4: "parcel sentence"}   # sentence index -> the short name drawn next to its arrow
ROW_NAMES = ["repay in full", "refund reaches card", "forgot password", "back to login page", "parcel ships", "shop is open",
             "opening times", "pay extra, delivery", "error E4410, payment"]
assert len(ROW_NAMES) == len(es.DOCS)


def arrow(x0, y0, x1, y1, stroke, dash=""):
    """A line from (x0, y0) to (x1, y1) with a filled head."""
    angle = math.atan2(y1 - y0, x1 - x0)
    head = [(x1, y1), (x1 - 16 * math.cos(angle - 0.4), y1 - 16 * math.sin(angle - 0.4)), (x1 - 16 * math.cos(angle + 0.4), y1 - 16 * math.sin(angle + 0.4))]
    d = f' stroke-dasharray="{dash}"' if dash else ""
    pts = " ".join(f"{x:.1f},{y:.1f}" for x, y in head)
    return [f'  <line x1="{x0:.1f}" y1="{y0:.1f}" x2="{x1 - 8 * math.cos(angle):.1f}" y2="{y1 - 8 * math.sin(angle):.1f}" stroke="{stroke}" stroke-width="4"{d}/>',
            f'  <polygon points="{pts}" fill="{stroke}"/>']


def angle_svg():
    q = es.embed(QUESTION)
    vectors = [es.embed(d) for d in es.DOCS]
    scores = {i: es.cosine(q, vectors[i]) for i in SHOWN}
    best = max(scores, key=scores.get)
    ox, oy, unit = 70.0, 340.0, 290.0                      # origin, and the length of a list of length 1
    money, delivery = es.TOPICS.index("money"), es.TOPICS.index("delivery")
    left_out = max(math.sqrt(sum(v[t] ** 2 for t in range(len(es.TOPICS)) if t not in (money, delivery))) for v in [q] + [vectors[i] for i in SHOWN])
    lines = [OPEN.format(w=620, h=380, grey=GREY),
             f"  <title>Four lists of numbers drawn as arrows in the money and delivery topics</title>",
             f"  <desc>The question &quot;{QUESTION}&quot; is an arrow. The pay-extra sentence points nearly the same way (cosine {scores[7]:.3f}), the parcel sentence points up the delivery axis (cosine {scores[4]:.3f}) and the repay sentence points along the money axis (cosine {scores[0]:.3f}). The picture leaves out the other two topics, where no arrow has more than {left_out:.2f} of its length.</desc>",
             '  <rect width="100%" height="100%" fill="#ffffff"/>',
             f'  <line x1="{ox:.0f}" y1="{oy:.0f}" x2="{ox + unit + 20:.0f}" y2="{oy:.0f}" stroke="{GREY}" stroke-width="2"/>',
             f'  <line x1="{ox:.0f}" y1="{oy:.0f}" x2="{ox:.0f}" y2="{oy - unit - 20:.0f}" stroke="{GREY}" stroke-width="2"/>',
             f'  <text x="{ox:.0f}" y="372" text-anchor="start" fill="{INK}">money topic</text>',
             f'  <text x="14" y="26" text-anchor="start" fill="{INK}">delivery topic</text>']
    lines += arrow(ox, oy, ox + q[money] * unit, oy - q[delivery] * unit, INK)
    lines.append(f'  <text x="{ox + q[money] * unit + 12:.1f}" y="{oy - q[delivery] * unit + 6:.1f}" text-anchor="start" fill="{INK}">question</text>')
    for i, name in SHOWN.items():
        v = vectors[i]
        x, y = ox + v[money] * unit, oy - v[delivery] * unit
        colour, dash = (GREEN, "") if i == best else (ORANGE, "9 7")
        lines += arrow(ox, oy, x, y, colour, dash)
        dy = 6 if v[delivery] > 0.9 else 5 if v[delivery] > 0 else -10
        lines.append(f'  <text x="{x + 12:.1f}" y="{y + dy:.1f}" text-anchor="start" fill="{INK}">{name} {scores[i]:.3f}</text>')
    lines.append("</svg>")
    return "\n".join(lines) + "\n"


def ranking_svg():
    q = es.QUERIES[0]
    words = dict(es.rank_keywords(q))
    meaning = dict(es.rank_meaning(q))
    top_words, top_meaning = es.rank_keywords(q)[0][0], es.rank_meaning(q)[0][0]
    scale = max(words.values())
    lines = [OPEN.format(w=640, h=420, grey=GREY),
             f"  <title>The same question searched by words and by meaning</title>",
             f"  <desc>For the question &quot;{q}&quot;, one bar per sentence. By words the top sentence is &quot;{es.DOCS[top_words]}&quot; with {words[top_words]} shared words, and {sum(1 for s in words.values() if s == 0)} of {len(es.DOCS)} sentences share none. By meaning the top sentence is &quot;{es.DOCS[top_meaning]}&quot; with a cosine of {meaning[top_meaning]:.3f}.</desc>",
             '  <rect width="100%" height="100%" fill="#ffffff"/>',
             f'  <text x="250" y="30" text-anchor="start" fill="{INK}">shared words</text>',
             f'  <text x="410" y="30" text-anchor="start" fill="{INK}">cosine</text>']
    for i, name in enumerate(ROW_NAMES):
        y = 52 + i * 36
        lines.append(f'  <text x="16" y="{y + 20}" text-anchor="start" fill="{INK}">{name}</text>')
        for x0, value, full, top, label in ((250, words[i], scale, top_words, str(words[i])), (410, meaning[i], 1.0, top_meaning, f"{meaning[i]:.3f}")):
            width = 110.0 * value / full
            colour = GREEN if i == top else INK
            if width > 0:
                lines.append(f'  <rect x="{x0}" y="{y}" width="{width:.1f}" height="26" fill="{colour}" stroke="{INK}" stroke-width="2"/>')
            lines.append(f'  <text x="{x0 + width + 10:.1f}" y="{y + 20}" text-anchor="start" fill="{INK}">{label}</text>')
    lines += [f'  <rect x="16" y="{52 + 9 * 36 + 4}" width="24" height="24" fill="{GREEN}" stroke="{INK}" stroke-width="2"/>',
              f'  <text x="50" y="{52 + 9 * 36 + 24}" text-anchor="start" fill="{INK}">top match of each search (first row of the ranking)</text>',
              "</svg>"]
    return "\n".join(lines) + "\n"


FILES = {"angle.svg": angle_svg, "ranking.svg": ranking_svg}


if __name__ == "__main__":
    drawn = {name: draw() for name, draw in FILES.items()}
    if "--check" in sys.argv:
        sys.exit(0 if all((FIGS / n).exists() and (FIGS / n).read_text(encoding="utf-8") == s for n, s in drawn.items()) else 1)
    FIGS.mkdir(exist_ok=True)
    for name, svg in drawn.items():
        (FIGS / name).write_text(svg, encoding="utf-8")
        print("wrote", FIGS / name)
show_numbers.py80 linesDownload show_numbers.py
Show code
"""Print every number the lesson quotes, from the toy in embed_search.py.

    uv run --no-project python show_numbers.py
"""
import embed_search as es

Q = es.QUERIES[0]
DOCS = es.DOCS


def vec(v):
    return "(" + ", ".join(f"{x:.3f}" for x in v) + ")"


def known(text):
    return [w for w in es.words(text) if w in es.WORD_VECTORS]


def raw_sum(text):
    return [sum(es.WORD_VECTORS[w][t] for w in known(text)) for t in range(len(es.TOPICS))]


print(f'1. Words only. Question: "{Q}"')
print("   content words:", ", ".join(es.content_words(Q)))
ranked = es.rank_keywords(Q)
for i, score in ranked[:3]:
    shared = ", ".join(es.shared_words(Q, DOCS[i])) or "none"
    print(f"   {score} shared  {DOCS[i]}  ({shared})")
print("   sentences sharing no word with the question:", sum(1 for _, s in ranked if s == 0), "of", len(DOCS))

print()
print("2. Meaning. Same question, closest 4 sentences (cosine):")
for i, score in es.rank_meaning(Q)[:4]:
    print(f"   {score:.3f}  {DOCS[i]}")

print()
print("3. One comparison by hand: the question and the refund sentence")
a, b = es.embed(Q), es.embed(DOCS[1])
print("   topics:", ", ".join(es.TOPICS))
print("   question words the toy knows:", ", ".join(known(Q)), "->", vec(a))
print("   sentence words the toy knows:", ", ".join(known(DOCS[1])), "->", vec(b))
print("   sentence before scaling:", vec(raw_sum(DOCS[1])), f"length {es.length(raw_sum(DOCS[1])):.3f}")
print(f"   dot = {es.dot(a, b):.3f}, lengths = {es.length(a):.1f} and {es.length(b):.1f}, cosine = {es.cosine(a, b):.3f}")

print()
print("4. Length does not change the cosine")
short_list, long_list = (1.0, 0.0, 0.0, 0.0), (5.0, 0.0, 0.0, 0.0)
print(f"   dot = {es.dot(short_list, long_list):.1f}, cosine = {es.cosine(short_list, long_list):.1f}")
print(f"   sharing nothing: cosine = {es.cosine(short_list, (0.0, 1.0, 0.0, 0.0)):.1f}")

print()
print("5. Every question: best sentence by words, best by meaning")
for q in es.QUERIES:
    kw_i, kw_s = es.rank_keywords(q)[0]
    me_i, me_s = es.rank_meaning(q)[0]
    kw = f"{kw_s} shared: {DOCS[kw_i]}" if kw_s else "no shared word"
    me = f"{me_s:.3f}: {DOCS[me_i]}" if me_s else "0.000, nothing to rank"
    print(f"   {q}")
    print(f"      words   {kw}")
    print(f"      meaning {me}")

print()
print("6. A question with no word the toy knows")
unknown = es.embed("Code E4410")
print("   vector:", vec(unknown), " cosines:", sorted({round(es.cosine(unknown, es.embed(d)), 3) for d in DOCS}))

print()
print("7. How many multiplications one question costs (documents x list length)")
for n_docs, dims in ((len(DOCS), 4), (1_000, 768), (1_000_000, 768)):
    print(f"   {n_docs:>9,} x {dims:>3} = {es.scan_cost(n_docs, dims):>11,}")

print()
print("8. Looking only in the closest cell(s). Question:", es.QUERIES[-1])
vectors = [es.embed(d) for d in DOCS]
q_vec = es.embed(es.QUERIES[-1])
exact = es.nearest(q_vec, vectors, 1)[0]
print(f"   all {len(DOCS)}: best is {DOCS[exact[0]]} at {exact[1]:.3f}")
for probes in (1, 2):
    best, count = es.cell_search(q_vec, vectors, probes)
    print(f"   {probes} cell{'s' if probes > 1 else ' '}: compared {count}, best is {DOCS[best]} at {es.cosine(q_vec, vectors[best]):.3f}")
test_embed_search.py116 linesDownload test_embed_search.py
Show code
"""Pins the toy in embed_search.py to what the lesson says about it."""
# guards: new lesson tool; the lesson's claims (words miss a paraphrase, meaning finds it, a cosine ignores length, an unknown word has no
# vector, one cell can miss) each rest on numbers the toy prints, and a toy edit must not leave the lesson saying something the code no longer does
import math
import re
import subprocess
import sys
from pathlib import Path

import pytest

import embed_search as es
import make_figs

VECTORS = [es.embed(d) for d in es.DOCS]
CODE = Path(__file__).resolve().parent
LESSON = (CODE.parent / "lesson.md").read_text(encoding="utf-8")
SOURCE = (CODE / "embed_search.py").read_text(encoding="utf-8")


def run(script, *args, cwd=CODE):
    return subprocess.run([sys.executable, str(script), *args], cwd=cwd, capture_output=True, text=True, check=True).stdout


def part(start, end):
    """The lesson text from one heading up to the next."""
    return LESSON.split(start, 1)[1].split(end, 1)[0]


def fences(text):
    return re.findall(r"```(\w+)\n(.*?)```", text, re.S)


# guards: a toy edit that changes which sentence each way of searching puts first, which the lesson's table of six questions quotes
@pytest.mark.parametrize("question, words_best, words_score, meaning_best, meaning_score", [
    ("Can I get my money back?", 3, 2, 0, 1.0),                       # words pick the login page (get, back); meaning picks the repay sentence
    ("I lost my password", 2, 1, 3, 0.998),
    ("When are you open?", 5, 1, 6, 1.0),                              # "open" does not match "Opening": no stemming
    ("Where is my order?", 0, 0, 4, 0.976),                            # no shared word at all: every sentence scores 0, list order wins
    ("Code E4410", 8, 1, 0, 0.0),                                      # no word the toy knows: every cosine is 0, list order wins
    ("Can I pay for delivery?", 7, 2, 7, 0.962),
])
def test_each_question_gets_the_words_best_and_the_meaning_best_the_lesson_names(question, words_best, words_score, meaning_best, meaning_score):
    assert es.rank_keywords(question)[0] == (words_best, words_score)
    index, score = es.rank_meaning(question)[0]
    assert index == meaning_best and score == pytest.approx(meaning_score, abs=5e-4)


# guards: someone swapping cosine for a plain dot product, which grows with the length of the lists and ranks a long list first; also the
# lesson's two side claims, that for length-1 lists the squared distance is 2 - 2 x cosine, and that embed is a sum so word order is ignored
def test_cosine_ignores_length_where_dot_does_not():
    short, long, other = (1.0, 0.0, 0.0, 0.0), (5.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0)
    assert es.dot(short, long) == 5.0 and es.cosine(short, long) == 1.0 and es.cosine(short, other) == 0.0
    assert es.cosine((0.0, 0.0, 0.0, 0.0), short) == 0.0                                       # an empty list divides by zero without the guard
    assert all(es.length(v) == pytest.approx(1.0) for v in VECTORS if any(v))                  # embed scales a known sentence to length 1
    assert math.dist(VECTORS[1], VECTORS[7]) ** 2 == pytest.approx(2 - 2 * es.cosine(VECTORS[1], VECTORS[7]))
    assert es.embed("refund card") == es.embed("card refund")


# guards: an unknown identifier: the toy has no numbers for it, so meaning search cannot rank anything while words still find the sentence
def test_a_question_with_no_known_word_has_a_zero_list_and_only_words_find_it():
    assert es.embed("Code E4410") == (0.0, 0.0, 0.0, 0.0)
    assert {score for _, score in es.rank_meaning("Code E4410")} == {0.0}
    assert es.shared_words("Code E4410", es.DOCS[8]) == ["e4410"]


# guards: the approximate-search claim: one cell is cheaper and can miss the best sentence, two cells find it again
def test_closest_cell_only_misses_what_two_cells_find():
    question = es.embed("Can I pay for delivery?")
    exact = es.nearest(question, VECTORS, 1)[0][0]
    assert exact == 7 and es.cell_search(question, VECTORS, 1) == (4, 1) and es.cell_search(question, VECTORS, 2) == (7, 5)
    assert es.cell_search(question, VECTORS, len(es.TOPICS)) == (exact, len(es.DOCS))           # every cell is the full scan
    assert es.scan_cost(1_000_000, 768) == 768_000_000


# guards: the lesson's "A real run" block drifting from what show_numbers.py prints, and its line cites drifting from embed_search.py after an edit
def test_the_real_run_block_and_the_line_cites_match_the_code():
    blocks = fences(part("### A real run", "\n## Your turn"))
    assert blocks[0] == ("bash", "cd code && uv run --no-project python show_numbers.py\n")
    assert blocks[1] == ("text", run("show_numbers.py"))
    lines = SOURCE.splitlines()
    cites = re.findall(r"`embed_search\.py:(\d+)`<br>`([^`]+)`", LESSON)
    assert len(cites) == 5 and all(lines[int(n) - 1].strip() == text for n, text in cites)
    in_prose = {100: "if length(a) == 0", 101: "return 0.0", 109: ".get(w, ())", 110: "total[i] += x", 111: "size = length(total)",
                117: "scored = [", 135: "def cell_of", 137: "return max(", 146: "return [i for c in order", 149: "def cell_search"}
    assert all(text in lines[n - 1] for n, text in in_prose.items())


# guards: a code block in "Go deeper" that no longer appears in embed_search.py, so a reader copies code the lesson never ran
def test_every_python_block_in_the_lesson_is_verbatim_in_the_code():
    blocks = [body.rstrip("\n") for lang, body in fences(LESSON) if lang == "python"]
    assert len(blocks) == 5 and all(block in SOURCE for block in blocks)


# guards: the "Your turn" step: the line to add, and the before and after output, must be what the toy prints (the edit is made on a copy)
def test_your_turn_edit_gives_the_output_the_lesson_shows(tmp_path):
    turn = part("## Your turn", "## What this means")
    line = re.search(r'add the line `("cash": \([^`]+\),)` inside', turn).group(1)
    question = re.search(r'embed_search\.py "([^"]+)"', turn).group(1)
    anchor = '    "money": (1.0, 0.0, 0.0, 0.0),\n'
    assert anchor in SOURCE
    (tmp_path / "embed_search.py").write_text(SOURCE.replace(anchor, anchor + "    " + line + "\n"), encoding="utf-8")
    before, after = [body for lang, body in fences(turn) if lang == "text"]
    assert before == run(CODE / "embed_search.py", question)
    assert after == run(tmp_path / "embed_search.py", question, cwd=tmp_path)


# guards: a figure that no longer matches what make_figs.py draws, or alt text that states a number the figure does not show
def test_figures_are_what_the_code_draws_and_their_alt_numbers_are_in_them():
    for name, draw in make_figs.FILES.items():
        assert (make_figs.FIGS / name).read_text(encoding="utf-8") == draw()
    shown = re.findall(r"!\[([^\]]*)\]\(figs/([^)]+)\)", LESSON)
    assert sorted(name for _, name in shown) == sorted(make_figs.FILES)
    for alt, name in shown:
        svg = (make_figs.FIGS / name).read_text(encoding="utf-8")
        assert all(number in svg for number in re.findall(r"\d+\.\d+", alt))
test_widget.py236 linesDownload test_widget.py
Show code
"""Guards for ../widget.html: its data block, its size, that its JavaScript ranks and scores like embed_search.py, and what a reader sees."""
# guards: new lesson tool; the widget copies the toy's numbers and steps into JavaScript, so a toy edit left out of widget.html, or JavaScript
# that ranks differently from Python, would show the reader numbers the lesson text does not print
import json
import re
import subprocess

import embed_search as es
from embed_widget import CONFIG_BLOCK, WIDGET, embed

HTML = WIDGET.read_text(encoding="utf-8")
ROOT = HTML[HTML.index('<div class="srch-root">'):HTML.index("<script")]
TOLERANCE = 1e-12                                   # the JavaScript and Python scores may differ by at most this much
MODES = ("words", "meaning", "cell")
VECTORS = [es.embed(d) for d in es.DOCS]

# Reads the steps out of the widget between its marker comments, runs them with Node, and compares every embedding (within 1e-12), and the
# order, shared words, score and compared-or-not flag of every row (exact, and within 1e-12 for the score), for every question and way of searching.
PARITY = r"""
import fs from 'node:fs';
const [fixture, widget, tolerance] = process.argv.slice(2);
const fx = JSON.parse(fs.readFileSync(fixture, 'utf8'));
const html = fs.readFileSync(widget, 'utf8');
const cfg = JSON.parse(html.match(/<script type="application\/json" id="srch-config">([\s\S]*?)<\/script>/)[1]);
const js = html.slice(html.indexOf('/* ---------- the model ('), html.indexOf('/* ---------- display'));
const api = new Function('cfg', "'use strict';" + js + '; return {embed: embed, rank: rank};')(cfg);
const tol = Number(tolerance), bad = [];
let checks = 0, worst = 0;
const near = (a, b) => { const d = Math.abs(a - b); worst = Math.max(worst, d); return d <= tol; };
fx.embeds.forEach(([text, want]) => {
  const got = api.embed(text);
  want.forEach((x, t) => { checks++; if (!near(got[t], x)) bad.push(['embed', text, t, got[t], x]); });
});
Object.keys(fx.ranks).forEach((key) => {
  const [qi, mode] = key.split('|'), got = api.rank(Number(qi), mode), want = fx.ranks[key];
  checks++;
  if (got.length !== want.length) { bad.push(['length', key]); return; }
  want.forEach((w, k) => {
    checks++;
    const g = got[k];
    if (g.i !== w.i || g.checked !== w.checked || JSON.stringify(g.shared) !== JSON.stringify(w.shared) || !near(g.score, w.score)) bad.push(['row', key, k, g, w]);
  });
});
console.log(JSON.stringify({ checks, worst, bad: bad.slice(0, 4) }));
process.exit(bad.length ? 1 : 0);
"""

# Runs the page script against a small stand-in for the DOM, presses every question and every way of searching, and reads back what a reader sees.
PAGE = r"""
import fs from 'node:fs';
const [widget, fixture] = process.argv.slice(2);
const html = fs.readFileSync(widget, 'utf8');
const fx = JSON.parse(fs.readFileSync(fixture, 'utf8'));
const config = html.match(/<script type="application\/json" id="srch-config">([\s\S]*?)<\/script>/)[1];
const code = html.match(/<script>([\s\S]*?)<\/script>/)[1];

function el(tag) {
  const e = { tag, children: [], listeners: {}, style: {}, attrs: {}, textContent: '' };
  e.setAttribute = (k, v) => { e.attrs[k] = v; };
  e.addEventListener = (type, f) => (e.listeners[type] = e.listeners[type] || []).push(f);
  e.appendChild = (c) => (e.children.push(c), c);
  return e;
}
function open() {
  const page = { root: el('html'), messages: [], parent: { other: true } };
  fx.ids.forEach((id) => { page[id] = el('x'); });
  page['srch-config'].textContent = config;
  const doc = { getElementById: (id) => page[id], createElement: el, documentElement: page.root };
  const win = { addEventListener: (type, f) => page.messages.push(f) };
  new Function('document', 'window', 'parent', code)(doc, win, page.parent);
  return page;
}
const fire = (e) => (e.listeners.click || []).forEach((f) => f({ target: e }));
const bad = [];
const want = (what, got, expected) => { if (JSON.stringify(got) !== JSON.stringify(expected)) bad.push([what, got, expected]); };
function look(page, qi, mode, what) {                // compares the page with Python's view of one question and one way of searching
  const v = fx.views[qi + '|' + mode], rows = page['srch-list'].children;
  const summary = page['srch-summary'].textContent;
  want(what + ': summary says', v.fragments.filter((f) => !summary.includes(f)), []);
  want(what + ': question pressed', page['srch-queries'].children.map((b) => b.attrs['aria-pressed']), fx.queries.map((q, k) => String(k === qi)));
  want(what + ': way pressed', page['srch-modes'].children.map((b) => b.attrs['aria-pressed']), fx.modes.map((m) => String(m === mode)));
  want(what + ': sentences in rank order', rows.map((li) => li.children[0].textContent), v.rows.map((r) => r.text));
  want(what + ': value column', rows.map((li) => li.children[1].children[1].textContent), v.rows.map((r) => r.value));
  want(what + ': bar widths', rows.map((li) => Number(parseFloat(li.children[1].children[0].children[0].style.width).toFixed(1))), v.rows.map((r) => Number(r.width.toFixed(1))));
  want(what + ': the best is marked', rows.map((li) => li.attrs['data-top']), v.rows.map((r) => String(r.top)));
  want(what + ': not compared say so', rows.map((li) => li.attrs['data-checked']), v.rows.map((r) => String(r.checked)));
  want(what + ': known words line', page['srch-known'].textContent, v.known);
}

const first = open();
look(first, fx.opening.query, fx.opening.mode, 'opening state');
want('nothing spoken yet', first['srch-live'].textContent, '');
want('question buttons', first['srch-queries'].children.map((b) => b.textContent), fx.queries);
want('way buttons', first['srch-modes'].children.map((b) => b.textContent), fx.labels);
want('note counts sentences and words', first['srch-note'].textContent.includes(fx.note), true);

// every question with every way of searching, by pressing the buttons
const page = open();
fx.queries.forEach((q, qi) => {
  fire(page['srch-queries'].children[qi]);
  fx.modes.forEach((mode, m) => {
    fire(page['srch-modes'].children[m]);
    look(page, qi, mode, q + ' / ' + mode);
    want(q + ' / ' + mode + ': spoken', page['srch-live'].textContent, page['srch-summary'].textContent);
  });
});

// the host page theme: only the parent window may set it, and only to light or dark
const themed = open();
const send = (data, source) => themed.messages.forEach((f) => f({ data, source }));
send({ type: 'spicyshark:theme', theme: 'dark' }, { other: false });
send({ type: 'spicyshark:theme', theme: 'purple' }, themed.parent);
send({ type: 'other', theme: 'dark' }, themed.parent);
send(null, themed.parent);
want('ignored messages', themed.root.attrs, {});
send({ type: 'spicyshark:theme', theme: 'dark' }, themed.parent);
want('theme from the parent', themed.root.attrs, { 'data-theme': 'dark' });
send({ type: 'spicyshark:theme', theme: 'light' }, themed.parent);
want('theme back to light', themed.root.attrs, { 'data-theme': 'light' });

console.log(JSON.stringify({ questions: fx.queries.length, bad: bad.slice(0, 5) }));
process.exit(bad.length ? 1 : 0);
"""


def run_node(tmp_path, script, fixture, args):
    (tmp_path / "fixture.json").write_text(json.dumps(fixture), encoding="utf-8")
    (tmp_path / "check.mjs").write_text(script, encoding="utf-8")
    run = subprocess.run(["node", str(tmp_path / "check.mjs"), *args(tmp_path)], capture_output=True, text=True, timeout=120)
    assert run.returncode == 0, run.stdout + run.stderr
    return json.loads(run.stdout)


def rows_for(qi, mode):
    """Python's answer for one question and way of searching: the rows best first, then the sentences that were not compared, in list order."""
    q = es.QUERIES[qi]
    qv = es.embed(q)
    if mode == "words":
        return [{"i": i, "score": s, "shared": es.shared_words(q, es.DOCS[i]), "checked": True} for i, s in es.rank_keywords(q)]
    checked = set(range(len(es.DOCS))) if mode == "meaning" else set(es.cells_checked(qv, VECTORS, 1))
    ranked = es.nearest(qv, VECTORS, len(es.DOCS))
    return ([{"i": i, "score": s, "shared": [], "checked": True} for i, s in ranked if i in checked]
            + [{"i": i, "score": es.cosine(qv, VECTORS[i]), "shared": [], "checked": False} for i in range(len(es.DOCS)) if i not in checked])


def view_for(qi, mode):
    """What the page should show: each row's sentence, value text, bar width and marks, and fragments the summary line must contain."""
    rows, q = rows_for(qi, mode), es.QUERIES[qi]
    best = rows[0]
    found = best["score"] > 0
    scale = max([1] + [len(es.shared_words(a, d)) for a in es.QUERIES for d in es.DOCS])
    out = []
    for k, r in enumerate(rows):
        if mode == "words":
            value = f"{len(r['shared'])} shared: " + ", ".join(r["shared"]) if r["shared"] else "0 shared"
            width = 100 * r["score"] / scale
        else:
            value = f"{r['score']:.3f}" if r["checked"] else "not compared"
            width = 100 * r["score"] if r["checked"] else 0
        out.append({"text": es.DOCS[r["i"]], "value": value, "width": width, "top": k == 0 and found, "checked": r["checked"]})
    doc = f"“{es.DOCS[best['i']]}”"
    if mode == "words":
        n = best["score"]
        fragments = [f"the top match shares {n} word{'s' if n != 1 else ''}", f"({', '.join(best['shared'])})", doc] if found else ["no sentence shares a word"]
    elif mode == "meaning":
        fragments = [doc, f"closeness {best['score']:.3f}"] if found else ["no word the toy knows"]
    else:
        everything = rows_for(qi, "meaning")[0]
        fragments = [f"compared {sum(r['checked'] for r in rows)} of {len(rows)} sentences"]
        fragments += ([doc, f"closeness {best['score']:.3f}", "also the closest of all" if everything["i"] == best["i"] else "it was not compared"]
                      if found else ["no word the toy knows"])
    known = [w for w in es.content_words(q) if w in es.WORD_VECTORS]
    return {"rows": out, "fragments": fragments, "known": "Words in the question that the toy has numbers for: " + (", ".join(known) or "none") + "."}


# guards: a toy edit that was not copied into widget.html (run embed_widget.py), and an embed that skips a drifted block
def test_widget_data_block_matches_the_python_toy():
    assert embed(HTML) == HTML
    drifted = HTML.replace('"opening": {"query": 0', '"opening": {"query": 1', 1).replace('"Code E4410"', '"Code E4411"', 1)
    assert drifted != HTML and embed(drifted) == HTML


# guards: a widget that never starts: the parity run covers only the formulas, so a misspelt id passes there and throws in the browser
def test_every_element_the_script_looks_up_exists_inside_the_root():
    script = HTML[HTML.index("<script>"):]
    lookups = set(re.findall(r"\$\('([\w-]+)'\)", script))
    missing = sorted(i for i in lookups if i != "srch-config" and f'id="{i}"' not in ROOT)
    assert not missing, missing
    assert 'id="srch-config"' in HTML


# guards: a widget that grows a network call, a form (it cannot submit in the sandboxed frame) or motion (nothing here switches it off)
def test_widget_is_small_and_asks_for_nothing_online():
    assert len(HTML.splitlines()) <= 260 and len(HTML.encode("utf-8")) < 40 * 1024
    page = CONFIG_BLOCK.sub("", HTML)
    for banned in ("http://", "https://", "fetch(", "XMLHttpRequest", "WebSocket", "sendBeacon", "import("):
        assert banned not in page, banned
    assert " src=" not in page and "@import" not in page
    assert "<form" not in HTML and 'type="submit"' not in HTML
    assert "transition" not in HTML and "animation" not in HTML
    assert "<details><summary>More settings</summary>" in ROOT and "<details open" not in ROOT


# guards: a widget that loses the page-theme listener (a white frame on a dark page) or takes a colour outside the site's palette
def test_widget_keeps_the_site_theme_listener_and_palette():
    assert "d.type !== 'spicyshark:theme'" in HTML and "e.source !== parent" in HTML and "parent === window" in HTML
    for pair in ("--bg: light-dark(#ffffff, #0a0f17)", "--panel: light-dark(#ebf0f6, #131b28)", "--ink: light-dark(#0a1626, #f4f7fb)",
                 "--mute: light-dark(#44566b, #a3b1c4)", "--ctl: light-dark(#66768a, #7a8a9f)", "--ink-on: light-dark(#f6f8fb, #05070c)",
                 "--green: light-dark(#00855F, #009E73)", ":root[data-theme=light]", ":root[data-theme=dark]"):
        assert pair in HTML, pair
    assert not set(re.findall(r"#[0-9a-fA-F]{3,8}\b", HTML)) - {"#ffffff", "#0a0f17", "#ebf0f6", "#131b28", "#0a1626", "#f4f7fb", "#44566b", "#a3b1c4",
                                                               "#66768a", "#7a8a9f", "#f6f8fb", "#05070c", "#00855F", "#009E73"}


# guards: the widget's JavaScript drifting from embed_search.py. Every embedding and score must agree within 1e-12 and every order, shared word
# and compared-or-not flag exactly; a toy edit that makes two sentences tie to within rounding shows up here as a different order
def test_widget_steps_rank_and_score_like_the_python_toy(tmp_path):
    fixture = {"embeds": [[t, es.embed(t)] for t in es.DOCS + es.QUERIES],
               "ranks": {f"{qi}|{mode}": rows_for(qi, mode) for qi in range(len(es.QUERIES)) for mode in MODES}}
    result = run_node(tmp_path, PARITY, fixture, lambda d: [str(d / "fixture.json"), str(WIDGET), str(TOLERANCE)])
    assert result["bad"] == [] and result["checks"] == (len(es.DOCS) + len(es.QUERIES)) * len(es.TOPICS) + len(es.QUERIES) * len(MODES) * (1 + len(es.DOCS))
    assert result["worst"] <= TOLERANCE


# guards: what a reader sees: every question and every way of searching shows Python's order, value text and bar widths, the best row is marked
# only when something matched, a sentence that was not compared says so, and the buttons speak
def test_widget_page_shows_what_the_lesson_names(tmp_path):
    opening = json.loads(CONFIG_BLOCK.search(HTML).group(2))["opening"]
    assert opening == es.config()["opening"] and opening["mode"] == "words" and es.QUERIES[opening["query"]] == "Can I get my money back?"
    assert 'class="srch-sr" id="srch-live" role="status" aria-live="polite" aria-atomic="true"' in ROOT
    ids = sorted(set(re.findall(r"\$\('([\w-]+)'\)", HTML[HTML.index("<script>"):])))
    fixture = {"ids": ids, "queries": es.QUERIES, "modes": list(MODES), "labels": ["Words only", "Meaning", "Meaning, one cell"], "opening": opening,
               "note": f"{len(es.DOCS)} sentences and {len(es.WORD_VECTORS)} words",
               "views": {f"{qi}|{mode}": view_for(qi, mode) for qi in range(len(es.QUERIES)) for mode in MODES}}
    result = run_node(tmp_path, PAGE, fixture, lambda d: [str(WIDGET), str(d / "fixture.json")])
    assert result == {"questions": len(es.QUERIES), "bad": []}