Translation
Translate text between languages with configurable models.
Translate text between languages using provider-agnostic translation models. Works with any provider that implements the TranslationModel interface.
See it in action
Try Translator and Smart Writer for working demos of these APIs.
Language detection
detectLanguage() identifies the language of a text string (110 languages,
ISO 639-1 codes) via the LanguageDetectionModel interface — implemented by
the @localmode/mediapipe provider. The SUPPORTED_LANGUAGES
constant maps codes to human-readable names, and the getLanguageName(code)
helper looks up a name with a fallback to the raw code for unknown languages.
translate()
Translate a single text:
import { translate } from '@localmode/core';
import { transformers } from '@localmode/transformers';
const model = transformers.translator('Xenova/opus-mt-en-de');
const { translation, usage, response } = await translate({
model,
text: 'Hello, how are you?',
});
console.log(translation); // 'Hallo, wie geht es Ihnen?'
console.log(usage.durationMs); // 120const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
const { translation } = await translate({
model,
text: 'Hello, how are you?',
abortSignal: controller.signal,
});TranslateOptions
Prop
Type
TranslateResult
Prop
Type
translateMany()
Translate multiple texts in a single call:
import { translateMany } from '@localmode/core';
const { translations } = await translateMany({
model,
texts: ['Hello', 'Goodbye', 'Thank you'],
});
translations.forEach((t) => console.log(t));
// 'Hallo', 'Auf Wiedersehen', 'Danke'Custom Provider
Implement the TranslationModel interface to create a custom translation provider:
import type { TranslationModel, DoTranslateOptions, DoTranslateResult } from '@localmode/core';
class MyTranslator implements TranslationModel {
readonly modelId = 'custom:my-translator';
readonly provider = 'custom';
readonly sourceLanguage = 'en';
readonly targetLanguage = 'de';
async doTranslate(options: DoTranslateOptions): Promise<DoTranslateResult> {
const { texts } = options;
// Your translation logic here
const translations = texts.map((text) => `[translated] ${text}`);
return {
translations,
usage: { inputTokens: texts.join('').length, outputTokens: translations.join('').length, durationMs: 0 },
};
}
}For recommended models, provider-specific options, and practical recipes, see the Transformers Translation guide.
Next Steps
Transformers Translation
Recommended translation models and usage.
Summarization
Summarize text with configurable length.