Answer From the Top Chunks

The search now finds the chunk a player means, even when the question names a card and a game. However, finding the right page isn’t an answer yet. In the first lesson, the model answered table 1’s question about Night Market’s card 23 with a firm “No”, because the card’s text never reached it.

In this lesson, you’ll send that text. You’ll write an answerQuestion() function that searches the rulebooks, puts the top chunks in the prompt, and asks the model for an answer with the IDs of the chunks it used. Then you’ll compare sending different numbers of chunks with pasting in every rulebook. Start with what the model receives.

Put the Top Chunks in the Prompt

The model has never seen the café’s rulebooks and can’t open them, so the chunks from search() have to go into its input. The instructions then ask it to base its answer on that text, not on whatever it picked up in training. Each chunk needs a clear border and a label. The border keeps rulebook text apart from the player’s question, and the label gives the model something short to point at when it says which rule it used.

The borders are delimiters, tags such as <chunk> and </chunk> that mark exactly where each piece of data starts and ends. Tags like these look like XML, but the names are yours to choose, as long as every chunk uses the same ones. Each <chunk> tag also carries the chunk’s id, game, and page as attributes. The IDs are the ones build-index.js saved, such as night-market-8.

This way of answering is called retrieval-augmented generation, or RAG. Your code retrieves the relevant text and adds it to the prompt. The model then generates an answer from it. Create answer.js in the project folder. Its first part holds the instructions and the function that builds the input:

Language: JavaScript Filename: answer.js
import { z } from "zod";
import { askForJson } from "./model/index.js";
import { search } from "./search.js";

const INSTRUCTIONS = `You answer rules questions for players
at a board-game café. The input holds the player's question
between <question> tags and rulebook chunks between <chunk>
tags. Answer only from those chunks, in two or three
sentences. In citations, list the id of every chunk your
answer uses.`;

export function escapeData(value) {
  return String(value)
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");
}

export function buildInput(question, chunks) {
  const blocks = chunks.map((chunk) => {
    const id = escapeData(chunk.id);
    const game = escapeData(chunk.game);
    const page = escapeData(chunk.page);
    const text = escapeData(chunk.text);
    const tag = `<chunk id="${id}" game="${game}" page="${page}">`;
    return `${tag}\n${text}\n</chunk>`;
  });
  return [
    `<question>\n${escapeData(question)}\n</question>`,
    ...blocks,
  ].join("\n\n");
}

The instructions tell the model where the data is and ask it to answer only from the chunks and list the IDs of the chunks its answer uses. Lists like that are called citations. They let a player see where a rule came from.

buildInput() turns each chunk into a block with .map(), puts the question first, and joins everything with a blank line between blocks.

Every value passes through escapeData() first, because the tags mark where data ends only if the data can’t contain tags of its own. The helper uses .replaceAll() to turn <, >, ", and & into codes such as &lt;, so a player who types </question> can’t close the question early.

Models generally treat these codes as the characters they stand for, though an answer that quotes the text can echo a code such as &amp;. Either way, the codes can’t open or close a tag.

None of the café’s rulebooks or questions contain these characters, so escaping doesn’t change the printouts below.

Before you pay for a call, print the input for table 1’s question to see what the model actually receives. Create show-prompt.js, which runs the search and buildInput() but doesn’t call the model:

Language: JavaScript Filename: show-prompt.js
import { readFile } from "node:fs/promises";
import { buildInput } from "./answer.js";
import { search } from "./search.js";

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

const chunks = await search(question.text, 4);
console.log(buildInput(question.text, chunks));

Run it with node --env-file=.env show-prompt.js. The script makes no model call, but answer.js imports model/index.js, which reads your settings when it loads. Here are the question and the first two of the four chunks, with the long lines wrapped for display:

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.