Build translation applications using Azure Translation SDKs for JavaScript (@azure-rest/ai-translation-text, @azure-rest/ai-translation-document). Use when implementing text translation, transliteration, language detection, or batch document translation.
Add this skill
npx mdskills install sickn33/azure-ai-translation-tsComprehensive Azure translation SDK reference with clear examples for text and document translation
1---2name: azure-ai-translation-ts3description: Build translation applications using Azure Translation SDKs for JavaScript (@azure-rest/ai-translation-text, @azure-rest/ai-translation-document). Use when implementing text translation, transliteration, language detection, or batch document translation.4package: "@azure-rest/ai-translation-text, @azure-rest/ai-translation-document"5---67# Azure Translation SDKs for TypeScript89Text and document translation with REST-style clients.1011## Installation1213```bash14# Text translation15npm install @azure-rest/ai-translation-text @azure/identity1617# Document translation18npm install @azure-rest/ai-translation-document @azure/identity19```2021## Environment Variables2223```bash24TRANSLATOR_ENDPOINT=https://api.cognitive.microsofttranslator.com25TRANSLATOR_SUBSCRIPTION_KEY=<your-api-key>26TRANSLATOR_REGION=<your-region> # e.g., westus, eastus27```2829## Text Translation Client3031### Authentication3233```typescript34import TextTranslationClient, { TranslatorCredential } from "@azure-rest/ai-translation-text";3536// API Key + Region37const credential: TranslatorCredential = {38 key: process.env.TRANSLATOR_SUBSCRIPTION_KEY!,39 region: process.env.TRANSLATOR_REGION!,40};41const client = TextTranslationClient(process.env.TRANSLATOR_ENDPOINT!, credential);4243// Or just credential (uses global endpoint)44const client2 = TextTranslationClient(credential);45```4647### Translate Text4849```typescript50import TextTranslationClient, { isUnexpected } from "@azure-rest/ai-translation-text";5152const response = await client.path("/translate").post({53 body: {54 inputs: [55 {56 text: "Hello, how are you?",57 language: "en", // source (optional, auto-detect)58 targets: [59 { language: "es" },60 { language: "fr" },61 ],62 },63 ],64 },65});6667if (isUnexpected(response)) {68 throw response.body.error;69}7071for (const result of response.body.value) {72 for (const translation of result.translations) {73 console.log(`${translation.language}: ${translation.text}`);74 }75}76```7778### Translate with Options7980```typescript81const response = await client.path("/translate").post({82 body: {83 inputs: [84 {85 text: "Hello world",86 language: "en",87 textType: "Plain", // or "Html"88 targets: [89 {90 language: "de",91 profanityAction: "NoAction", // "Marked" | "Deleted"92 tone: "formal", // LLM-specific93 },94 ],95 },96 ],97 },98});99```100101### Get Supported Languages102103```typescript104const response = await client.path("/languages").get();105106if (isUnexpected(response)) {107 throw response.body.error;108}109110// Translation languages111for (const [code, lang] of Object.entries(response.body.translation || {})) {112 console.log(`${code}: ${lang.name} (${lang.nativeName})`);113}114```115116### Transliterate117118```typescript119const response = await client.path("/transliterate").post({120 body: { inputs: [{ text: "这是个测试" }] },121 queryParameters: {122 language: "zh-Hans",123 fromScript: "Hans",124 toScript: "Latn",125 },126});127128if (!isUnexpected(response)) {129 for (const t of response.body.value) {130 console.log(`${t.script}: ${t.text}`); // Latn: zhè shì gè cè shì131 }132}133```134135### Detect Language136137```typescript138const response = await client.path("/detect").post({139 body: { inputs: [{ text: "Bonjour le monde" }] },140});141142if (!isUnexpected(response)) {143 for (const result of response.body.value) {144 console.log(`Language: ${result.language}, Score: ${result.score}`);145 }146}147```148149## Document Translation Client150151### Authentication152153```typescript154import DocumentTranslationClient from "@azure-rest/ai-translation-document";155import { DefaultAzureCredential } from "@azure/identity";156157const endpoint = "https://<translator>.cognitiveservices.azure.com";158159// TokenCredential160const client = DocumentTranslationClient(endpoint, new DefaultAzureCredential());161162// API Key163const client2 = DocumentTranslationClient(endpoint, { key: "<api-key>" });164```165166### Single Document Translation167168```typescript169import DocumentTranslationClient from "@azure-rest/ai-translation-document";170import { writeFile } from "node:fs/promises";171172const response = await client.path("/document:translate").post({173 queryParameters: {174 targetLanguage: "es",175 sourceLanguage: "en", // optional176 },177 contentType: "multipart/form-data",178 body: [179 {180 name: "document",181 body: "Hello, this is a test document.",182 filename: "test.txt",183 contentType: "text/plain",184 },185 ],186}).asNodeStream();187188if (response.status === "200") {189 await writeFile("translated.txt", response.body);190}191```192193### Batch Document Translation194195```typescript196import { ContainerSASPermissions, BlobServiceClient } from "@azure/storage-blob";197198// Generate SAS URLs for source and target containers199const sourceSas = await sourceContainer.generateSasUrl({200 permissions: ContainerSASPermissions.parse("rl"),201 expiresOn: new Date(Date.now() + 24 * 60 * 60 * 1000),202});203204const targetSas = await targetContainer.generateSasUrl({205 permissions: ContainerSASPermissions.parse("rwl"),206 expiresOn: new Date(Date.now() + 24 * 60 * 60 * 1000),207});208209// Start batch translation210const response = await client.path("/document/batches").post({211 body: {212 inputs: [213 {214 source: { sourceUrl: sourceSas },215 targets: [216 { targetUrl: targetSas, language: "fr" },217 ],218 },219 ],220 },221});222223// Get operation ID from header224const operationId = new URL(response.headers["operation-location"])225 .pathname.split("/").pop();226```227228### Get Translation Status229230```typescript231import { isUnexpected, paginate } from "@azure-rest/ai-translation-document";232233const statusResponse = await client.path("/document/batches/{id}", operationId).get();234235if (!isUnexpected(statusResponse)) {236 const status = statusResponse.body;237 console.log(`Status: ${status.status}`);238 console.log(`Total: ${status.summary.total}`);239 console.log(`Success: ${status.summary.success}`);240}241242// List documents with pagination243const docsResponse = await client.path("/document/batches/{id}/documents", operationId).get();244const documents = paginate(client, docsResponse);245246for await (const doc of documents) {247 console.log(`${doc.id}: ${doc.status}`);248}249```250251### Get Supported Formats252253```typescript254const response = await client.path("/document/formats").get();255256if (!isUnexpected(response)) {257 for (const format of response.body.value) {258 console.log(`${format.format}: ${format.fileExtensions.join(", ")}`);259 }260}261```262263## Key Types264265```typescript266// Text Translation267import type {268 TranslatorCredential,269 TranslatorTokenCredential,270} from "@azure-rest/ai-translation-text";271272// Document Translation273import type {274 DocumentTranslateParameters,275 StartTranslationDetails,276 TranslationStatus,277} from "@azure-rest/ai-translation-document";278```279280## Best Practices2812821. **Auto-detect source** - Omit `language` parameter to auto-detect2832. **Batch requests** - Translate multiple texts in one call for efficiency2843. **Use SAS tokens** - For document translation, use time-limited SAS URLs2854. **Handle errors** - Always check `isUnexpected(response)` before accessing body2865. **Regional endpoints** - Use regional endpoints for lower latency287
Full transparency — inspect the skill content before installing.