Split the Rulebooks Into Chunks

In the last exercise, you ranked a handful of stored rule sentences against a player’s question. The rules desk needs more than a handful, though. Its answers live somewhere in eight rulebooks of four to seven pages each, and nobody has cut those books into neat sentences for you.

In this lesson, you’ll find out what goes wrong when you embed a whole rulebook as one text. You’ll then write a chunker that splits each book into small pieces, keeping the game and page with every piece, so that in later lessons you can search them and cite where an answer came from. Start with the most direct idea: one vector per rulebook.

Embed a Whole Rulebook

Your ranking already works for sentences, and a rulebook is a longer text, so the first thing to try is one vector per book. Question 3 is a good test. It comes from table 6, where two players finished Copper Canyon Express with the same amount of gold:

Language: JSON
{
  "id": 3,
  "table": 6,
  "text": "In Copper Canyon Express, two of us ended on 41 gold. Who wins?"
}

Several scripts in this lesson compare vectors, so move similarity() out of rank-rules.js into a module of its own. Create similarity.js in the project folder:

Language: JavaScript Filename: similarity.js
export function similarity(a, b) {
  let sum = 0;
  for (let i = 0; i < a.length; i++) {
    sum += a[i] * b[i];
  }
  return sum;
}

The function is unchanged, and the export keyword lets other scripts import it. Next, create whole-books.js. It embeds question 3, then embeds every file in data/rulebooks/ whole and prints each book’s score:

Language: JavaScript Filename: whole-books.js
import { readFile, readdir } from "node:fs/promises";
import { embed } from "./embed.js";
import { similarity } from "./similarity.js";

const text = await readFile("data/questions.json", "utf8");
const questions = JSON.parse(text);
const question = questions.find((entry) => entry.id === 3);
const questionVector = await embed(question.text);

const folder = "data/rulebooks";
for (const fileName of await readdir(folder)) {
  const book = await readFile(`${folder}/${fileName}`, "utf8");
  const score = similarity(questionVector, await embed(book));
  console.log(score.toFixed(3), fileName);
}

Node.js’s readdir() from node:fs/promises returns the names of the files in a folder. Run the script with node whole-books.js:

Language: Program Output
0.495 copper-canyon-express.txt
0.135 glasshouse.txt
0.222 lantern-harbor.txt
0.124 moth-and-lamp.txt
0.202 night-market.txt
0.267 orchard-rush.txt
0.279 summit-relay.txt
0.275 tidepool-traders.txt

Copper Canyon Express comes out on top, well ahead of the other seven, so this approach looks like it works. However, the answer to table 6 is on the last page, page 7, under “Breaking a Tie.” Did the book’s vector come from that page, or only from the game’s name? To find out, add these lines to the end of whole-books.js. They embed the whole book again and a copy without page 7, then compare the two vectors number by number:

Language: JavaScript Filename: whole-books.js
const book = await readFile(`${folder}/copper-canyon-express.txt`, "utf8");
const cut = book.slice(0, book.indexOf("== Page 7 =="));
const bookVector = await embed(book);
const cutVector = await embed(cut);
console.log("Without page 7:", similarity(questionVector, cutVector));
console.log("Whole book:", similarity(questionVector, bookVector));
const same = bookVector.every((value, i) => value === cutVector[i]);
console.log("Same vector?", same);

The scores print in full this time, so that a small difference can’t hide behind rounding. Before you run the script again, predict the new lines. Page 7 is the only page that answers the question, so how far will the score drop without it?

The eight book scores print as before, and then:

Language: Program Output
Without page 7: 0.4945154851668221
Whole book: 0.4945154851668221
Same vector? true

The score doesn’t drop at all. The two vectors are identical, all 384 numbers of them, so page 7 never reached the model.

The cut happens before the model runs. The pipeline from @huggingface/transformers first passes each text through the model’s tokenizer, which splits text into tokens. The tokenizer keeps only the first 512 tokens and drops the rest without an error or a warning. Copper Canyon Express runs to 844 of this model’s tokens, and page 7 starts after token 781, so the whole book and the book without its last page get the same vector.

Every rulebook in the project is longer than the limit, so every book vector you made ignored its last pages. The score of 0.495 came from the game’s name and its first pages, and the tie-breaker played no part in it.

A book short enough to fit would still be a risky match. One vector for a whole book averages setup, turns, scoring, and endings into one point, so a question about one rule has to compete with everything else the book covers, which can dilute the match. And a match on a whole book can’t tell a player which page to read.

The fix is to chunk each document: split it into chunks, pieces small enough for the model’s limit that each cover one topic, and record where each chunk came from. Then each chunk gets its own vector.

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.