Translation · Translate a batch of texts in one call2 / 3

Translate a batch of texts in one call

Example on GitHub(packages/sdk/examples/translation/translation-bergamot-batch.ts)

Now that you can translate one string, it's time to hand Bergamot several at once.

The text field also takes an array, and the engine works through the whole batch in one request. modelId, modelType and stream: false are unchanged.

We can swap the single string for the array as follows:

const result = translate({
  modelId,
  text: texts,
  modelType: "nmtcpp-translation",
  stream: false,
});

The output changes too: an array resolves result.translations instead of result.text. Each entry lines up with the same index in texts, so texts[i] gives you the source for translation:

const translations = await result.translations;
translations.forEach((translation, i) => {
  console.log(`${i + 1}. ${texts[i]} -> "${translation}"`);
});

The engine translates every entry before the loop above logs a line, so a long list stays silent while it runs.

Note: one modelConfig covers the batch, so from and to apply to every entry. Mixed source languages need a separate call per pair.

Questions

Question 1 of 3

When text is an array, what does result.translations resolve to?

Question 2 of 3

What is the primary advantage of one batch request over invoking translate() once per string?

Question 3 of 3

What do all the entries passed in a single text array share?

index.ts
Loading editor...

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