azure-ai-translation-ts
npx machina-cli add skill microsoft/skills/azure-ai-translation-ts --openclawAzure Translation SDKs for TypeScript
Text and document translation with REST-style clients.
Installation
# Text translation
npm install @azure-rest/ai-translation-text @azure/identity
# Document translation
npm install @azure-rest/ai-translation-document @azure/identity
Environment Variables
TRANSLATOR_ENDPOINT=https://api.cognitive.microsofttranslator.com
TRANSLATOR_SUBSCRIPTION_KEY=<your-api-key>
TRANSLATOR_REGION=<your-region> # e.g., westus, eastus
Text Translation Client
Authentication
import TextTranslationClient, { TranslatorCredential } from "@azure-rest/ai-translation-text";
// API Key + Region
const credential: TranslatorCredential = {
key: process.env.TRANSLATOR_SUBSCRIPTION_KEY!,
region: process.env.TRANSLATOR_REGION!,
};
const client = TextTranslationClient(process.env.TRANSLATOR_ENDPOINT!, credential);
// Or just credential (uses global endpoint)
const client2 = TextTranslationClient(credential);
Translate Text
import TextTranslationClient, { isUnexpected } from "@azure-rest/ai-translation-text";
const response = await client.path("/translate").post({
body: {
inputs: [
{
text: "Hello, how are you?",
language: "en", // source (optional, auto-detect)
targets: [
{ language: "es" },
{ language: "fr" },
],
},
],
},
});
if (isUnexpected(response)) {
throw response.body.error;
}
for (const result of response.body.value) {
for (const translation of result.translations) {
console.log(`${translation.language}: ${translation.text}`);
}
}
Translate with Options
const response = await client.path("/translate").post({
body: {
inputs: [
{
text: "Hello world",
language: "en",
textType: "Plain", // or "Html"
targets: [
{
language: "de",
profanityAction: "NoAction", // "Marked" | "Deleted"
tone: "formal", // LLM-specific
},
],
},
],
},
});
Get Supported Languages
const response = await client.path("/languages").get();
if (isUnexpected(response)) {
throw response.body.error;
}
// Translation languages
for (const [code, lang] of Object.entries(response.body.translation || {})) {
console.log(`${code}: ${lang.name} (${lang.nativeName})`);
}
Transliterate
const response = await client.path("/transliterate").post({
body: { inputs: [{ text: "这是个测试" }] },
queryParameters: {
language: "zh-Hans",
fromScript: "Hans",
toScript: "Latn",
},
});
if (!isUnexpected(response)) {
for (const t of response.body.value) {
console.log(`${t.script}: ${t.text}`); // Latn: zhè shì gè cè shì
}
}
Detect Language
const response = await client.path("/detect").post({
body: { inputs: [{ text: "Bonjour le monde" }] },
});
if (!isUnexpected(response)) {
for (const result of response.body.value) {
console.log(`Language: ${result.language}, Score: ${result.score}`);
}
}
Document Translation Client
Authentication
import DocumentTranslationClient from "@azure-rest/ai-translation-document";
import { DefaultAzureCredential } from "@azure/identity";
const endpoint = "https://<translator>.cognitiveservices.azure.com";
// TokenCredential
const client = DocumentTranslationClient(endpoint, new DefaultAzureCredential());
// API Key
const client2 = DocumentTranslationClient(endpoint, { key: "<api-key>" });
Single Document Translation
import DocumentTranslationClient from "@azure-rest/ai-translation-document";
import { writeFile } from "node:fs/promises";
const response = await client.path("/document:translate").post({
queryParameters: {
targetLanguage: "es",
sourceLanguage: "en", // optional
},
contentType: "multipart/form-data",
body: [
{
name: "document",
body: "Hello, this is a test document.",
filename: "test.txt",
contentType: "text/plain",
},
],
}).asNodeStream();
if (response.status === "200") {
await writeFile("translated.txt", response.body);
}
Batch Document Translation
import { ContainerSASPermissions, BlobServiceClient } from "@azure/storage-blob";
// Generate SAS URLs for source and target containers
const sourceSas = await sourceContainer.generateSasUrl({
permissions: ContainerSASPermissions.parse("rl"),
expiresOn: new Date(Date.now() + 24 * 60 * 60 * 1000),
});
const targetSas = await targetContainer.generateSasUrl({
permissions: ContainerSASPermissions.parse("rwl"),
expiresOn: new Date(Date.now() + 24 * 60 * 60 * 1000),
});
// Start batch translation
const response = await client.path("/document/batches").post({
body: {
inputs: [
{
source: { sourceUrl: sourceSas },
targets: [
{ targetUrl: targetSas, language: "fr" },
],
},
],
},
});
// Get operation ID from header
const operationId = new URL(response.headers["operation-location"])
.pathname.split("/").pop();
Get Translation Status
import { isUnexpected, paginate } from "@azure-rest/ai-translation-document";
const statusResponse = await client.path("/document/batches/{id}", operationId).get();
if (!isUnexpected(statusResponse)) {
const status = statusResponse.body;
console.log(`Status: ${status.status}`);
console.log(`Total: ${status.summary.total}`);
console.log(`Success: ${status.summary.success}`);
}
// List documents with pagination
const docsResponse = await client.path("/document/batches/{id}/documents", operationId).get();
const documents = paginate(client, docsResponse);
for await (const doc of documents) {
console.log(`${doc.id}: ${doc.status}`);
}
Get Supported Formats
const response = await client.path("/document/formats").get();
if (!isUnexpected(response)) {
for (const format of response.body.value) {
console.log(`${format.format}: ${format.fileExtensions.join(", ")}`);
}
}
Key Types
// Text Translation
import type {
TranslatorCredential,
TranslatorTokenCredential,
} from "@azure-rest/ai-translation-text";
// Document Translation
import type {
DocumentTranslateParameters,
StartTranslationDetails,
TranslationStatus,
} from "@azure-rest/ai-translation-document";
Best Practices
- Auto-detect source - Omit
languageparameter to auto-detect - Batch requests - Translate multiple texts in one call for efficiency
- Use SAS tokens - For document translation, use time-limited SAS URLs
- Handle errors - Always check
isUnexpected(response)before accessing body - Regional endpoints - Use regional endpoints for lower latency
Source
git clone https://github.com/microsoft/skills/blob/main/.github/plugins/azure-sdk-typescript/skills/azure-ai-translation-ts/SKILL.mdView on GitHub Overview
This skill provides REST-style Azure Translation clients for JavaScript/TypeScript. It covers text translation, transliteration, language detection, and batch document translation using @azure-rest/ai-translation-text and @azure-rest/ai-translation-document, with endpoint and credential-based authentication. Ideal for building multilingual apps and localization workflows.
How This Skill Works
Install the REST clients and authenticate with an endpoint and credentials. Use client.path('/translate').post, client.path('/languages').get, client.path('/transliterate').post, and client.path('/detect').post to send inputs and read structured results. For documents, use the DocumentTranslationClient to perform batch translations.
When to Use It
- Build real-time or batch text translation with optional transliteration and language detection in your app.
- Create a batch document translation workflow to translate many files at scale.
- Auto-detect source language to route content to the correct translation path.
- Populate UI language menus by fetching supported languages from /languages.
- Develop multilingual features like localized content and chat with per-language translations.
Quick Start
- Step 1: Install the SDKs: npm install @azure-rest/ai-translation-text @azure/identity and npm install @azure-rest/ai-translation-document @azure/identity
- Step 2: Create credentials and endpoint using environment variables or DefaultAzureCredential; e.g., new TextTranslationClient(endpoint, credential).
- Step 3: Call translate, languages, transliterate, or detect endpoints to translate text or transliterate and read results.
Best Practices
- Securely store and reference TRANSLATOR_ENDPOINT, TRANSLATOR_SUBSCRIPTION_KEY, and TRANSLATOR_REGION; prefer environment variables or managed identities.
- Prefer using auto-detect by omitting the source language or using the detect endpoint when routing content.
- Always handle isUnexpected(response) to catch API errors and surface response.body.error.
- When translating, loop over response.body.value to access translations for each input and target language.
- Use /languages to populate UI language options and cache results to minimize repeated calls.
Example Use Cases
- Translate 'Hello, how are you?' from English to Spanish and French using the /translate endpoint.
- Translate with options: set textType (Plain/Html) and per-language settings like tone or profanityAction.
- List supported translation languages to build a language picker UI.
- Transliterate non-Latin text, e.g., Chinese to Latn, to display readable scripts.
- Detect the language of a text sample and log the detected language and score.