Text embeddings · Embed many strings at once3 / 5

Embed many strings at once

Example on GitHub(packages/sdk/examples/embed-p2p.ts)

In the previous lesson we embedded one string at a time. That works for learning, but if we've got a thousand documents we don't want a thousand round-trips.

embed() accepts a string or a string array. Pass an array, get back an array of vectors.

The array overload of embed() is the same call with text as string[]. Pass a string[] and the batch call returns { embedding: number[][] } like so:

const { embedding: batchEmbeddings } = await embed({
  modelId,
  text: texts,
});
console.log(`Input: ${texts.length} texts`);
console.log(`Output: ${batchEmbeddings.length} embeddings`);
console.log(`Each embedding dimensions: ${batchEmbeddings[0]!.length}`);

Each inner array is one 1024-number vector, in the same order as the input. The model stays loaded, so the second call is much faster than the first (only the embedding step runs).

Note: batchEmbeddings[0] is the first vector, batchEmbeddings[0][0] is the very first number of that vector. Mind your brackets if you start indexing.

Questions

Question 1 of 3

What changes about embed()'s return value when text is a string array instead of a single string?

Question 2 of 3

What has to be true for batching strings together to run faster than embedding them one at a time?

Question 3 of 3

Given texts has 3 strings, what does batchEmbeddings.length equal?

index.ts
Loading editor...

Run your code, check your answer, or ask a question. It all shows up here.