Embed Every Chunk Once

At the end of the last lesson, the café’s eight rulebooks became 90 chunks, each one labeled with its game, page, and heading. None of them has a vector yet, and a search can’t rank a chunk for a player’s question until that chunk has a vector.

In this lesson, you’ll embed every chunk once, ahead of time, and save the vectors to a file. You’ll make that build skip the chunks that haven’t changed, and then you’ll write the search() function that the rest of the course calls with each player’s question. The first question is when to embed the chunks.

Embed Every Chunk Ahead of Time

Every script so far has embedded its texts each time it ran. rank-rules.js calls embed() on each of its five rules inside the loop, right after it embeds the question. That was fine for five sentences. A search built the same way would embed all 90 chunks for every question a player asks, even though the rulebooks haven’t changed since the last one.

The fix is to split the work into two phases. Indexing happens ahead of time: chunk the rulebooks, embed every chunk, and save the results as an index, a file of chunks with their vectors. Querying happens once per question: embed the question with the same model, and compare its vector with the saved ones. The diagram below shows which work belongs to which phase:

Rulebooks become chunks, embedded once into index.json. Each question is embedded with the same model and compared with it.
Chunks Embedded Once, One Embedding per Question

The only embedding a player now waits for is the one for their question. The index also follows a rule from the lesson Choose Where Embeddings Come From. Every vector is stored with its text and the name of the model that made it, because you can compare a question’s vector only with vectors from the same model.

The index script needs the model’s name, and embed.js already exports it as MODEL_NAME. You added that export in the last lesson so that chunks.js could load the model’s tokenizer. Create build-index.js in the project folder. Its first part collects the chunks, as split-rulebooks.js did, and its second part embeds each chunk and saves the records:

Language: JavaScript Filename: build-index.js
import { readFile, readdir, writeFile } from "node:fs/promises";
import { chunkRulebook } from "./chunks.js";
import { embed, MODEL_NAME } from "./embed.js";

const folder = "data/rulebooks";
const chunks = [];
for (const fileName of await readdir(folder)) {
  const text = await readFile(`${folder}/${fileName}`, "utf8");
  chunks.push(...chunkRulebook(fileName, text));
}

const started = performance.now();
const records = [];
for (const chunk of chunks) {
  const vector = await embed(chunk.text);
  records.push({ ...chunk, model: MODEL_NAME, vector });
}
const seconds = (performance.now() - started) / 1000;
console.log(`Embedded ${records.length} chunks in ${seconds.toFixed(1)} s`);

const json = JSON.stringify(records);
await writeFile("index.json", json);
const kib = Buffer.byteLength(json, "utf8") / 1024;
console.log(`Saved index.json: ${Math.round(kib)} KiB`);

Each record copies the chunk’s id, game, page, heading, and text with spread syntax, then adds model and vector. Node.js’s global performance.now() returns the milliseconds since the script started, so the difference between two calls times the loop.

JSON.stringify() turns the records into text, and writeFile() saves that text, replacing the file if it already exists.

Buffer.byteLength() counts the bytes that the text takes up in the file. json.length would undercount them once a letter such as the é in café appears. Dividing the bytes by 1024 gives kibibytes (KiB). If you need a refresher on reading and writing files in Node.js, the Timers and Files course covers it.

Run the script with node build-index.js:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.