Turn Text Into Vectors

The model in the last lesson needed the right rulebook page, and finding that page is your code’s job. A word search won’t get far. Table 6 asked whether they could trade with “someone who isn’t next to me,” and Lantern Harbor’s page 4 answers with “Where players sit at the table doesn’t matter for trading.” The question and the rule share hardly any words, yet they’re about the same thing.

In this lesson, you’ll turn a rule into a list of numbers with a small model that runs on your own computer. You’ll write the embed() helper that the rest of the course builds on, then look closely at what it returns. Start with the kind of model that does this work.

Meet a Model That Returns Numbers

To compare a question with a rule by meaning, your code needs something it can measure, and text isn’t that. An embedding model reads a text and returns an embedding: a fixed-length list of numbers, also called a vector. The model was trained so that texts with similar meanings get similar vectors, even when they use different words. That’s what lets your code look for table 6’s rule by meaning instead of by words.

Map coordinates work in a similar way. Two cafés on the same street have close coordinates, so you can tell they’re near each other from the numbers alone. Rules that mean similar things get vectors that sit close together in the same sense.

The comparison breaks down at the numbers themselves, though. A map position has two numbers, and you can name what each one measures. This model’s vectors have hundreds, and no single one of them means anything you could label.

An embedding model isn’t the model behind ask(). It doesn’t generate text, and you can’t ask it a question. It only returns numbers. The one this course uses, all-MiniLM-L6-v2, is small enough to run on your own machine. It needs no API key, costs nothing per call, and embeds text without sending it to a provider.

Later in the course, answering a question sends that question and a few selected rulebook chunks to your provider through ask(), and the answer comes back from it.

The project’s package.json lists @huggingface/transformers, a package that runs models like this one in JavaScript, and npm install in the first lesson installed it. If you’re starting the course here, run npm install in the project folder first:

Language: Shell
$ npm install

The model needs no .env entry and no account. The package downloads it the first time your code asks for it.

Write the embed() Helper

Every later step embeds text, from the rulebook chunks to each player’s question, so the model goes behind one small function that the rest of the project imports. Create embed.js in the project folder:

Language: JavaScript Filename: embed.js
import { pipeline } from "@huggingface/transformers";

const MODEL_NAME = "Xenova/all-MiniLM-L6-v2";

const extractor = await pipeline("feature-extraction", MODEL_NAME);

export async function embed(text) {
  const output = await extractor(text, {
    pooling: "mean",
    normalize: true,
  });
  return Array.from(output.data);
}

The package’s pipeline() function sets up a task with a model. The "feature-extraction" task turns text into vectors, and MODEL_NAME names a copy of all-MiniLM-L6-v2 on Hugging Face, the site the package downloads models from.

The pipeline() call sits at the top of the module with await, outside embed(). A module’s top-level code runs once, the first time a script imports it. Therefore, the model loads once, and every embed() call reuses the same extractor.

Inside embed(), the model first produces one vector for each of the text’s tokens, the pieces of words it reads. This model splits text its own way, so its tokens aren’t the ones your provider bills you for. The option pooling: "mean" averages those token vectors into one vector for the whole text. Then normalize: true scales that vector so that its size is 1, up to rounding, which keeps the comparison in the next lesson short.

The extractor returns the package’s own object for a grid of numbers, and its .data property is a Float32Array, one of JavaScript’s typed arrays.

Array.from() copies it into a plain array. A plain array prints readably, and it survives JSON.stringify() when the course saves vectors to a file later.

Look at a Real Vector

The helper’s return value is unlike anything ask() gave you, so look at one before you build on it. Create try-embed.js in the project folder. It embeds the Lantern Harbor rule from page 4 and logs the result:

Language: JavaScript Filename: try-embed.js
import { embed } from "./embed.js";

const rule =
  "Where players sit at the table doesn't matter for trading.";
const vector = await embed(rule);

console.log("Array?", Array.isArray(vector));
console.log("Length:", vector.length);
console.log("First five:", vector.slice(0, 5));
console.log("Magnitude:", Math.hypot(...vector));

Run it with node try-embed.js. You don’t need --env-file=.env this time because nothing here calls your provider. The first run pauses while the package downloads the model, about 90 MB, once. It keeps the files in a cache folder inside node_modules/@huggingface/transformers/, so later runs start in about a second.

That first run needs a connection to Hugging Face, and because the cache is inside node_modules, a fresh install downloads the model again. A real deployment would fetch it once, when the app is built, but that’s beyond this course, and the cached copy is all you need here. Here’s a real run:

Language: Program Output
Array? true
Length: 384
First five: [
  0.08264119923114777,
  -0.027607593685388565,
  -0.09466604143381119,
  -0.03861166909337044,
  0.027734020724892616
]
Magnitude: 0.9999998775281884

Your numbers should match, though the last few digits can differ on another machine. embed() returned a plain array of 384 small numbers, both positive and negative. Read the first five again: nothing in them says “trading” or “seating.” That’s the map comparison’s limit at work. The meaning is in how the whole vector sits relative to other vectors, not in any one number.

If that idea still feels slippery, the button above opens the mentor with that question, and you can follow up with your own.

The last line confirms the normalization. Math.hypot() returns the square root of the sum of the squares, the vector’s size measured from zero. The small difference from 1 is due to floating-point rounding.

The rule has ten words. Table 6’s players will also type short questions, and some chunks of a rulebook will be long. Add these lines to the end of try-embed.js to embed a single word:

Language: JavaScript Filename: try-embed.js
const word = await embed("Trading");
console.log("One word:", word.length);

Before you run the script again, predict the new last line. Will one word give a shorter vector than ten?

The earlier lines don’t change, and the new one gives the same length as the sentence:

Language: Program Output
One word: 384

Every text gets 384 numbers. The model makes one vector for each token, and mean pooling averages however many there are into one vector of the same length. So you can compare a one-word text with a whole sentence number by number.

The model sets that length, whatever text you give it. In one run with only MODEL_NAME changed to a larger model, Xenova/all-mpnet-base-v2, the same rule came back with 768 numbers. That model is a download of over 400 MB, so you needn’t try it. Vectors from different models can’t be compared. Choosing a model gets a lesson of its own later in this course. That’s all you need to know about other models for now.

Two results from this lesson can blur together: every text gets 384 numbers, and every vector has a size of about 1. The first comes from the model and mean pooling, and the second comes from normalize: true. If you’re unsure how they differ, the button below opens the mentor with that question:

Check Your Understanding

These questions use embed.js and try-embed.js from this lesson. Answer them before you open the answers:

  1. Table 4’s question about Night Market has nineteen words. How many numbers will embed() return for it, and how many for a question twice as long?
  2. A colleague suggests skipping the local model and asking ask() to “describe this rule as a list of numbers.” Why does the course use an embedding model instead?
  3. Why does embed.js call pipeline() outside embed() instead of inside it?
  4. Which of the five numbers you printed tells you the rule is about trading?
  1. embed() returns 384 numbers for both questions. Mean pooling turns any number of token vectors into one vector, and the model sets its length, regardless of the text.
  2. The model behind ask() generates text. What comes back would only look like numbers, and nothing would make similar rules get nearby values. Every call would also cost money and send the rulebooks to your provider. An embedding model is trained to place similar meanings close together, returns its vector directly, and runs on your machine.
  3. The module’s top-level code runs once, so the model loads once and every call reuses extractor. Inside embed(), every call would load the model all over again.
  4. None of them tells you that. A single number means nothing on its own. The meaning is in how a whole vector relates to other vectors from the same model.

You can now turn any rule or question into 384 numbers, but a vector on its own doesn’t answer table 6 yet. In the next lesson, Rank Texts by Meaning, you’ll compare two vectors with one short function and watch the closest rule rise to the top of a list.

Become a Member to join the conversation.