translate( )
Translates text from one language to another using a specified translation model.
function translate(params): {
tokenStream: AsyncGenerator<string>;
text: Promise<string>;
stats: Promise<TranslationStats | undefined>;
};
Supports both NMT (Neural Machine Translation) and LLM models.
| Name | Type | Required? | Default | Description |
|---|
| params.modelId | string | ✓ | — | The identifier of the translation model |
| params.text | string | string[] | ✓ | — | The input text(s) to translate. NMT supports array; LLM only string. |
| params.modelType | "nmt" | "llm" | ✓ | — | The type of translation model |
| params.stream | boolean | ✗ | true | Whether to stream tokens or return complete response |
| params.from | string | ✗ | auto-detect | Source language code (LLM only) |
| params.to | string | ✓ (LLM) | — | Target language code (LLM only) |
| params.context | string | ✗ | — | Additional context for translation (LLM only) |
object — Object with the following fields:
| Field | Type | Description |
|---|
| tokenStream | AsyncGenerator<string> | Stream of translated tokens |
| text | Promise<string> | Complete translated text |
| stats | Promise<TranslationStats | undefined> | Translation statistics |
| Field | Type | Description |
|---|
| processedTokens | number | Number of tokens processed |
| Error | When |
|---|
TRANSLATION_FAILED | Translation fails |
// Streaming mode (default)
const result = translate({
modelId: "nmt-model",
text: "Hello world",
from: "en",
to: "es",
modelType: "llm",
});
for await (const token of result.tokenStream) {
process.stdout.write(token);
}
// Non-streaming mode
const response = translate({
modelId: "nmt-model",
text: "Hello world",
from: "en",
to: "es",
modelType: "llm",
stream: false,
});
console.log(await response.text);