home / skills / sickn33 / antigravity-awesome-skills / azure-ai-translation-ts

azure-ai-translation-ts skill

/skills/azure-ai-translation-ts

This skill helps you build translation apps using Azure Translation SDKs, enabling text and document translation with language detection and batching.

npx playbooks add skill sickn33/antigravity-awesome-skills --skill azure-ai-translation-ts

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
7.1 KB
---
name: azure-ai-translation-ts
description: 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.
package: "@azure-rest/ai-translation-text, @azure-rest/ai-translation-document"
---

# Azure Translation SDKs for TypeScript

Text and document translation with REST-style clients.

## Installation

```bash
# Text translation
npm install @azure-rest/ai-translation-text @azure/identity

# Document translation
npm install @azure-rest/ai-translation-document @azure/identity
```

## Environment Variables

```bash
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

```typescript
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

```typescript
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

```typescript
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

```typescript
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

```typescript
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

```typescript
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

```typescript
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

```typescript
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

```typescript
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

```typescript
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

```typescript
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

```typescript
// 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

1. **Auto-detect source** - Omit `language` parameter to auto-detect
2. **Batch requests** - Translate multiple texts in one call for efficiency
3. **Use SAS tokens** - For document translation, use time-limited SAS URLs
4. **Handle errors** - Always check `isUnexpected(response)` before accessing body
5. **Regional endpoints** - Use regional endpoints for lower latency

Overview

This skill helps you build translation applications using Azure Translation SDKs for JavaScript, covering text and document translation, transliteration, and language detection. It provides patterns for authenticating, calling translation endpoints, batching documents with SAS URLs, and handling responses and errors. Use it to integrate Azure's REST-style translation clients into web services, tools, or batch pipelines.

How this skill works

The skill shows how to instantiate TextTranslationClient and DocumentTranslationClient with API key or token credentials, then call REST endpoints for translate, transliterate, detect, and document translation. For documents it demonstrates single-file and batch workflows using multipart/form-data or Azure Blob SAS URLs and provides examples for polling status and listing translated documents. It also includes examples for retrieving supported languages and file formats and for checking unexpected responses.

When to use it

  • Implementing real-time text translation or language detection in a web or server application
  • Transliterating scripts (e.g., Chinese Hans -> Latin) for UI or search normalization
  • Translating single documents via multipart upload from a service
  • Running large-scale batch translations using Azure Blob storage and SAS URLs
  • Fetching supported languages or file formats to power UI selectors

Best practices

  • Omit the source language to let the service auto-detect when input language is unknown
  • Group multiple texts into one translate call to reduce latency and request overhead
  • Use short-lived SAS tokens for batch document translation to limit exposure and control access
  • Always check isUnexpected(response) or response status before using response.body to avoid runtime errors
  • Prefer regional endpoints to reduce latency and align with data residency requirements

Example use cases

  • Build a multilingual chat or messaging service that translates messages on the fly
  • Create a content pipeline that batch-translates document sets stored in Azure Blob Storage using SAS URLs
  • Add UI controls that list supported languages and formats for user selection before submitting translation jobs
  • Implement a transliteration feature to convert non-Latin scripts to Latin for search indexing or display

FAQ

Which credentials can I use to authenticate?

You can authenticate with an API key and region or with a TokenCredential such as DefaultAzureCredential. Text and document clients accept either pattern shown in the examples.

How do I translate many documents securely?

Upload documents to Azure Blob Storage and generate short-lived SAS URLs for source and target containers, then start a batch translation job and poll its operation ID for status.

How should I handle errors from the service?

Always check isUnexpected(response) or response.status before accessing response.body; throw or surface the returned error object to callers for safe handling.