For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
Primary navigation

Web QA with embeddings

How to build an AI that can answer questions about your website.

This tutorial walks through an example of crawling a website (in this example, the OpenAI website), turning the crawled pages into embeddings using the Embeddings API, and then creating a basic search functionality that allows a user to ask questions about the embedded information. This is intended to be a starting point for more sophisticated applications that make use of custom knowledge bases.

Getting started

Before starting, set up an OpenAI API key and work through the quickstart tutorial.

Download and extract the TypeScript sample archive. From the extracted typescript-examples directory, run pnpm install --ignore-workspace --frozen-lockfile. The lockfile pins OpenAI, Cheerio, CSV, tokenizer, and canvas dependencies. Set OPENAI_API_KEY before the API steps.

Run each complete program separately from the same working directory with node --experimental-strip-types tutorial-crawl-website-embeddings/<filename>.ts. Do not concatenate the excerpts: each file includes its own imports and setup. Run crawl-website, build-scraped-dataframe, tokenize-scraped-text, split-long-text, visualize-chunk-token-counts, create-embeddings, and answer-question in that order. The hyperlink helpers share one program; context retrieval, answering, and test questions share answer-question.ts.

Replace https://example.com with your website’s URL in the crawler, hyperlink, and scraped-data programs. Replace {{MODEL}} in the downloaded answering program with the model shown below. The crawler saves text under text; later stages produce processed/scraped.csv, processed/chunks.json, and processed/embeddings.csv. Run create-embeddings before answering questions; the package’s synthetic CSV fixtures are only for local analysis tests.

Set OPENAI_API_KEY before running examples in your selected language.

For Java, use these tested Maven dependencies: com.openai:openai-java:4.105.0, org.jsoup:jsoup:1.24.1, org.apache.commons:commons-csv:1.14.1, com.knuddels:jtokkit:1.1.0, and com.fasterxml.jackson.core:jackson-databind:2.18.11. Use one Java class for the four crawler excerpts, one class for the three final question-answering excerpts, and a separate class for each intermediate example. In each Java file, put imports at the top, place executable statements in a main method that declares checked exceptions, and place helper methods, fields, and records at class scope. Set OPENAI_API_KEY and run the classes in order from your IDE or build tool, with the Maven dependencies on the runtime classpath. Use the same working directory so each program can read the preceding program’s text/ and processed/ outputs.

Setting up a web crawler

Choose a website you can crawl. Expand the steps below to collect page text for the embeddings.

Building an embeddings index

DALL-E: Woman turning a stack of papers into numbers pixel art

CSV is a common format for storing embeddings. You can use this format with Python by converting the raw text files (which are in the text directory) into Pandas data frames. Pandas is a popular open source library that helps you work with tabular data (data stored in rows and columns).

Blank empty lines can clutter the text files and make them harder to process. A function can remove those lines and tidy up the files.

Clean the scraped text
function removeNewlines(texts: string[]): string[] {
  return texts.map((text) =>
    text.replaceAll("\n", " ").replaceAll("\\n", " ").replace(/ {2,}/g, " ")
  );
}

Converting the text to CSV requires looping through the text files in the text directory created earlier. After opening each file, remove the extra spacing and append the modified text to a list. Then, add the text with the new lines removed to an empty Pandas data frame and write the data frame to a CSV file.

Extra spacing and new lines can clutter the text and complicate the embeddings process. The code used here helps to remove some of them but you may find 3rd party libraries or other methods useful to get rid of more unnecessary characters.

Save scraped pages as a dataset
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { stringify } from "csv-stringify/sync";

const address = new URL("https://example.com");
const directory = path.join("text", address.host);
const rows: { fname: string; text: string }[] = [];
const entries = await readdir(directory, { withFileTypes: true });
entries.sort((a, b) => a.name.localeCompare(b.name));
for (const entry of entries) {
  if (!entry.isFile() || !entry.name.endsWith(".txt")) continue;
  let title = entry.name.slice(0, -4).replace(/#[a-f0-9]{64}$/, "");
  if (title === address.host || title === `${address.host}_`) title = "index";
  else if (title.startsWith(`${address.host}_`))
    title = title.slice(address.host.length + 1);
  title = title.replaceAll("#update", "").replace(/[-_]/g, " ");
  const content = await readFile(path.join(directory, entry.name), "utf8");
  const text = content
    .replaceAll("\n", " ")
    .replaceAll("\\n", " ")
    .replace(/ {2,}/g, " ");
  rows.push({ fname: title, text: `${title}. ${text}` });
}
await mkdir("processed", { recursive: true });
await writeFile(
  "processed/scraped.csv",
  stringify(rows, {
    header: true,
    columns: ["fname", "text"],
  })
);

The next step is tokenization after saving the raw text into a CSV file. This process splits the input text into tokens by breaking down the sentences and words. A visual demonstration of this can be seen by checking out our tokenizer in the docs.

A helpful rule of thumb is that one token generally corresponds to ~4 characters of text for common English text. This translates to roughly Âľ of a word (so 100 tokens ~= 75 words).

The API has a limit on the maximum number of input tokens for embeddings. To stay below the limit, the text in the CSV file needs to be broken down into multiple rows. The existing length of each row will be recorded first to identify which rows need to be split.

Count tokens in scraped pages
import { readFile, writeFile } from "node:fs/promises";
import { createCanvas } from "@napi-rs/canvas";
import { getEncoding } from "js-tiktoken";
const encoding = getEncoding("cl100k_base");
import { parse } from "csv-parse/sync";
const rows: { text: string }[] = parse(
  await readFile("processed/scraped.csv", "utf8"),
  { columns: true, skip_empty_lines: true }
);
const texts = rows.map((row) => row.text);
const counts = texts.map((text) => encoding.encode(text).length);
const bins = Array<number>(10).fill(0);
const maximum = Math.max(1, ...counts);
for (const count of counts)
  bins[Math.min(9, Math.floor((count / maximum) * 10))]++;
const canvas = createCanvas(800, 600);
const context = canvas.getContext("2d");
context.fillStyle = "white";
context.fillRect(0, 0, 800, 600);
context.fillStyle = "black";
context.font = "20px sans-serif";
context.fillText("Token counts", 40, 30);
const largestBin = Math.max(1, ...bins);
context.fillStyle = "steelblue";
for (const [index, count] of bins.entries()) {
  const height = (count / largestBin) * 480;
  context.fillRect(40 + index * 72, 540 - height, 68, height);
}
context.fillStyle = "black";
context.fillText("0", 40, 575);
context.fillText(String(maximum), 740, 575);
await writeFile("token-histogram.png", await canvas.encode("png"));
Embeddings histogram

Split longer pages into chunks that fit within the embedding model’s input limit.

Split long pages into chunks
import { readFile, writeFile } from "node:fs/promises";
import { parse } from "csv-parse/sync";
import { getEncoding } from "js-tiktoken";

const encoding = getEncoding("cl100k_base");
function splitIntoMany(text: string, maxTokens = 500): string[] {
  if (!Number.isInteger(maxTokens) || maxTokens <= 0) {
    throw new Error("maxTokens must be a positive integer");
  }
  if (!text.trim()) return [];
  const sentences = text.split(". ");
  const chunks: string[] = [];
  let chunk = "";
  for (const [index, part] of sentences.entries()) {
    const sentence = index < sentences.length - 1 ? `${part}.` : part;
    if (encoding.encode(sentence).length > maxTokens) {
      throw new Error("Split the oversized sentence before chunking");
    }
    const candidate = chunk ? `${chunk} ${sentence}` : sentence;
    if (encoding.encode(candidate).length > maxTokens) {
      chunks.push(chunk);
      chunk = sentence;
    } else chunk = candidate;
  }
  if (chunk) chunks.push(chunk);
  return chunks;
}

const rows: { text: string }[] = parse(
  await readFile("processed/scraped.csv", "utf8"),
  { columns: true, skip_empty_lines: true }
);
const chunks = rows.flatMap((row) => splitIntoMany(row.text));
await writeFile("processed/chunks.json", JSON.stringify(chunks));

Visualizing the updated histogram again can help to confirm if the rows were successfully split into shortened sections.

Visualize token counts after splitting
import { readFile, writeFile } from "node:fs/promises";
import { createCanvas } from "@napi-rs/canvas";
import { getEncoding } from "js-tiktoken";
const encoding = getEncoding("cl100k_base");
const texts: string[] = JSON.parse(
  await readFile("processed/chunks.json", "utf8")
);
const counts = texts.map((text) => encoding.encode(text).length);
const bins = Array<number>(10).fill(0);
const maximum = Math.max(1, ...counts);
for (const count of counts)
  bins[Math.min(9, Math.floor((count / maximum) * 10))]++;
const canvas = createCanvas(800, 600);
const context = canvas.getContext("2d");
context.fillStyle = "white";
context.fillRect(0, 0, 800, 600);
context.fillStyle = "black";
context.font = "20px sans-serif";
context.fillText("Token counts", 40, 30);
const largestBin = Math.max(1, ...bins);
context.fillStyle = "steelblue";
for (const [index, count] of bins.entries()) {
  const height = (count / largestBin) * 480;
  context.fillRect(40 + index * 72, 540 - height, 68, height);
}
context.fillStyle = "black";
context.fillText("0", 40, 575);
context.fillText(String(maximum), 740, 575);
await writeFile("token-histogram.png", await canvas.encode("png"));
Embeddings tokenized output

Create an embedding for each chunk with text-embedding-3-small. Use the same model for query embeddings. If you change embedding models, rebuild the index before searching it.

For the C# example, first export the text column of the chunked df to processed/chunks.json as a JSON array of strings. The example reads those chunks and writes the embeddings used by the question-answering step.

Create embeddings for the scraped text
import OpenAI from "openai";
import { readFile, writeFile } from "node:fs/promises";
import { stringify } from "csv-stringify/sync";

const client = new OpenAI();
const chunks: string[] = JSON.parse(
  await readFile("processed/chunks.json", "utf8")
);
if (
  !Array.isArray(chunks) ||
  !chunks.every((text) => typeof text === "string")
) {
  throw new Error("Expected an array of text chunks");
}
const rows: (string | number)[][] = [["text", "n_tokens", "embeddings"]];
for (const text of chunks) {
  const response = await client.embeddings.create({
    model: "text-embedding-3-small",
    input: text,
  });
  if (
    response.data.length !== 1 ||
    response.data[0].index !== 0 ||
    !response.data[0].embedding.length
  ) {
    throw new Error("Expected one embedding per chunk");
  }
  rows.push([
    text,
    response.usage.prompt_tokens,
    JSON.stringify(response.data[0].embedding),
  ]);
}
await writeFile("processed/embeddings.csv", stringify(rows));

This should take about 3-5 minutes but after you will have your embeddings ready to use!

Building a question answer system with your embeddings

DALL-E: Friendly robot question and answer system pixel art

Embed the user’s question and compare it with the indexed chunks to find the most relevant text. Send that text and the question to the Responses API to generate an answer.


Load the saved embeddings as numeric vectors: NumPy arrays in Python or lists in Java. The Java embedding step preserves the text and n_tokens columns alongside each vector in processed/embeddings.csv, which the answer program reads.

Load the saved embeddings
import { readFile } from "node:fs/promises";
import { parse } from "csv-parse/sync";

const records: { text: string; embeddings: string }[] = parse(
  await readFile("processed/embeddings.csv", "utf8"),
  { columns: true, skip_empty_lines: true }
);
const rows = records.map((row) => ({
  text: row.text,
  embedding: JSON.parse(row.embeddings) as number[],
}));
if (!rows.length) throw new Error("No embeddings");
const dimensions = rows[0].embedding.length;
for (const row of rows) {
  if (
    !Array.isArray(row.embedding) ||
    !dimensions ||
    row.embedding.length !== dimensions ||
    !row.embedding.every(Number.isFinite)
  ) {
    throw new Error("Expected finite embeddings with consistent dimensions");
  }
}
console.log(rows[0].embedding);

For Java, combine the next three excerpts—the context builder, answer function, and question calls—into one class. Collect their imports at the top. Place the Page record and helper methods at class scope; put the client setup, CSV loading, and question calls in the same main method.

Embed the question using the same model you used to build the index. Compare the vectors using cosine similarity and retrieve the closest text chunks.

Build context for a question
import OpenAI from "openai";
import { readFile } from "node:fs/promises";
import { parse } from "csv-parse/sync";

interface EmbeddedRow {
  text: string;
  nTokens: number;
  embedding: number[];
}
async function loadEmbeddings(path: string): Promise<EmbeddedRow[]> {
  const records: { text: string; n_tokens: string; embeddings: string }[] =
    parse(await readFile(path, "utf8"), {
      columns: true,
      skip_empty_lines: true,
    });
  const rows = records.map((row) => ({
    text: row.text,
    nTokens: Number(row.n_tokens),
    embedding: JSON.parse(row.embeddings) as number[],
  }));
  if (!rows.length) throw new Error("No embeddings");
  const dimensions = rows[0].embedding.length;
  for (const row of rows) {
    if (
      typeof row.text !== "string" ||
      !Number.isInteger(row.nTokens) ||
      row.nTokens < 0 ||
      !Array.isArray(row.embedding) ||
      !dimensions ||
      row.embedding.length !== dimensions ||
      !row.embedding.every(Number.isFinite)
    ) {
      throw new Error("Invalid embedded row");
    }
  }
  return rows;
}
function cosineSimilarity(a: number[], b: number[]): number {
  if (a.length !== b.length || !a.length || !a.every(Number.isFinite))
    throw new Error("Invalid embedding dimensions or values");
  const dot = a.reduce((sum, value, i) => sum + value * b[i], 0);
  const norm = Math.sqrt(
    a.reduce((sum, value) => sum + value * value, 0) *
      b.reduce((sum, value) => sum + value * value, 0)
  );
  if (!(norm > 0)) throw new Error("Embedding must have a nonzero norm");
  return dot / norm;
}
async function createContext(
  client: OpenAI,
  question: string,
  rows: EmbeddedRow[],
  maxTokens = 1800
): Promise<string> {
  const response = await client.embeddings.create({
    model: "text-embedding-3-small",
    input: question,
  });
  if (response.data.length !== 1)
    throw new Error("Expected one query embedding");
  const ranked = rows
    .map((row) => ({
      row,
      similarity: cosineSimilarity(response.data[0].embedding, row.embedding),
    }))
    .sort((a, b) => b.similarity - a.similarity);
  const parts: string[] = [];
  let tokens = 0;
  for (const { row } of ranked) {
    tokens += row.nTokens + 4;
    if (tokens > maxTokens) break;
    parts.push(row.text);
  }
  return parts.join("\n\n###\n\n");
}

The max_len argument in Python, or maxTokens in Java, limits how many tokens of retrieved text to include. Pass that text and the question to the Responses API using gpt-6-luna. The example extracts the response’s output text.

Answer a question from the website
async function answerQuestion(
  client: OpenAI,
  rows: EmbeddedRow[],
  question: string
): Promise<string> {
  const context = await createContext(client, question, rows);
  const response = await client.responses.create({
    model: "gpt-6-luna",
    instructions:
      'Answer the question using only the supplied context. If the context does not answer the question, say "I don\'t know."',
    input: `Context: ${context}\n\nQuestion: ${question}`,
  });
  if (response.status !== "completed")
    throw new Error(`Response ended with status ${response.status}`);
  return response.output_text.trim();
}

Ask a question the indexed pages can answer, then ask one they cannot. If the index contains a description of ChatGPT, the first call should answer from it. The second should return “I don’t know.”

Try example questions
const client = new OpenAI();
const rows = await loadEmbeddings("processed/embeddings.csv");
for (const question of [
  "What is ChatGPT?",
  "What did I have for breakfast today?",
]) {
  console.log(await answerQuestion(client, rows, question));
}

If the system is not able to answer a question that is expected, it is worth searching through the raw text files to see if the information that is expected to be known actually ended up being embedded or not. The crawling process that was done initially was setup to skip sites outside the original domain that was provided, so it might not have that knowledge if there was a subdomain setup.

Currently, the data frame is being passed in each time to answer a question. For more production workflows, a vector database solution should be used instead of storing the embeddings in a CSV file, but the current approach is a great option for prototyping.