SDK Usage Guide

Updated at:
Copy as MD

Billing notes

OpenAPI calls themselves incur no additional charges. Billing occurs only when the translation task actually runs, deducted in Credits. The billing rules are exactly the same as those in the console.

  • Uploading a file (UploadTranslationFile) is free of charge and only provides estimated Credits consumption.

  • Billing starts after submitting a translation task (SubmitTranslationTask).

  • After a task is cancelled, all frozen Credits are fully refunded.

Warning

Ensure the account has enough Credits before submitting a translation task. You can use the CreditsAvailable field returned by UploadTranslationFile as a preliminary reference; the submission result is final. If the balance is insufficient, SubmitTranslationTask returns Credits.NotEnough.

For detailed billing and deduction order, see Billing.

Product information

Item

Value

Endpoint

realtranslationagent.aliyuncs.com

Product Code

RealTranslationAgent

API version

2026-06-22

Install the SDK

// Add the dependency to pom.xml:
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>realtranslationagent20260622</artifactId>
    <version>1.0.2</version>
</dependency>
pip install alibabacloud_realtranslationagent20260622==1.0.2
npm install @alicloud/realtranslationagent20260622@1.0.2
go get github.com/alibabacloud-go/realtranslationagent-20260622/client@v1.0.2
dotnet add package AlibabaCloud.SDK.RealTranslationAgent20260622 --version 1.0.2
composer require alibabacloud/realtranslationagent-20260622 1.0.2
vcpkg install alibabacloud-sdk-realtranslationagent-20260622
// Add the dependency via Swift Package Manager in Package.swift:
.package(url: "https://github.com/alibabacloud-sdk-swift/realtranslationagent-20260622", from: "1.0.2")

Initialize the client

import com.aliyun.realtranslationagent20260622.Client;
import com.aliyun.teaopenapi.models.Config;

Config config = new Config()
        .setAccessKeyId("your-access-key-id")
        .setAccessKeySecret("your-access-key-secret")
        .setEndpoint("realtranslationagent.aliyuncs.com");

Client client = new Client(config);
from alibabacloud_realtranslationagent20260622.client import Client
from alibabacloud_tea_openapi.models import Config

config = Config(
    access_key_id="your-access-key-id",
    access_key_secret="your-access-key-secret",
    endpoint="realtranslationagent.aliyuncs.com"
)

client = Client(config)
import Client from '@alicloud/realtranslationagent20260622';
import { Config } from '@alicloud/openapi-client';

const config = new Config({
    accessKeyId: 'your-access-key-id',
    accessKeySecret: 'your-access-key-secret',
    endpoint: 'realtranslationagent.aliyuncs.com',
});

const client = new Client(config);
import (
    client "github.com/alibabacloud-go/realtranslationagent-20260622/client"
    openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    "github.com/alibabacloud-go/tea/tea"
)

config := &openapi.Config{
    AccessKeyId:     tea.String("your-access-key-id"),
    AccessKeySecret: tea.String("your-access-key-secret"),
    Endpoint:        tea.String("realtranslationagent.aliyuncs.com"),
}

c, err := client.NewClient(config)
using AlibabaCloud.SDK.RealTranslationAgent20260622;
using AlibabaCloud.OpenApiClient.Models;

var config = new Config
{
    AccessKeyId = "your-access-key-id",
    AccessKeySecret = "your-access-key-secret",
    Endpoint = "realtranslationagent.aliyuncs.com"
};

var client = new Client(config);
use AlibabaCloud\SDK\RealTranslationAgent\V20260622\RealTranslationAgent;
use Darabonba\OpenApi\Models\Config;

$config = new Config([
    'accessKeyId' => 'your-access-key-id',
    'accessKeySecret' => 'your-access-key-secret',
    'endpoint' => 'realtranslationagent.aliyuncs.com',
]);

$client = new RealTranslationAgent($config);

Workflow overview

image

Core flows in detail

Flow 1: Upload → Submit → Poll → Download

This is the most common translation flow, suitable for new document translation.

  1. Upload file and preview estimate

    Call UploadTranslationFile to upload the document and obtain the parsed result and estimate.

    The API returns:

    • TaskId — Unique identifier for subsequent operations

    • WordCount / PageCount — Word and page counts

    • EstimatedCostCredits — Estimated Credits consumption

    • DetectedLang — Automatically detected source language

    • Fonts — Available target fonts

    • SensitiveDetected — Whether sensitive content was detected

    Note

    This step incurs no charge. You can decide whether to proceed to translation based on the estimate.

  2. Submit the translation task

    After confirming the estimate, call SubmitTranslationTask to formally submit the translation task.

    Required parameters:

    • TaskId — Task ID obtained in the previous step

    • Config — Translation config (source/target language, font, etc.)

    • CustomTerms (optional) — Custom term pairs

    After successful submission, the task enters the PENDING state and automatically starts processing.

  3. Poll task progress

    Call GetTranslationTask to poll the task status and progress.

    Recommended polling interval is 3–5 seconds, until the status reaches a terminal value:

    • COMPLETED — Translation finished, the translated file can be downloaded

    • FAILED — Translation failed, check ErrorMessage

    • CANCELLED — Cancelled

  4. Download the translated file

    After the task is completed, call GetTranslatedFileUrl to obtain a temporary download link for the translated file.

    To download the original file, call GetOriginalFileUrl.

    Note

    Download links are valid for 1 hour by default; re-obtain the link after expiry.

Flow 2: cancel a translation task

During task processing, you can call CancelTranslationTask to cancel it. Upon successful cancellation, all frozen Credits are fully refunded.

Flow 3: query historical tasks

Call ListTranslationTasks to paginate through historical task lists, filterable by status, language, file name, and time range.

Flow 4: retranslate

To retranslate an existing task, call SubmitTranslationTask with BaseTaskId (the historical task ID) instead of TaskId. No need to re-upload the file.

Task status reference

Status

Description

Available actions

ANALYZED

File uploaded and analyzed

Submit translation

PENDING

Task submitted, awaiting processing

Cancel task

PROCESSING

Translation in progress

Cancel task, query progress

COMPLETED

Translation finished

Download translated / original file

FAILED

Translation failed

View error message

CANCELLED

Cancelled

—

Full code examples

Java

import com.aliyun.realtranslationagent20260622.Client;
import com.aliyun.realtranslationagent20260622.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class TranslationExample {

    public static void main(String[] args) throws Exception {
        // 1. Initialize the client
        Config config = new Config()
                .setAccessKeyId("your-access-key-id")
                .setAccessKeySecret("your-access-key-secret")
                .setEndpoint("realtranslationagent.aliyuncs.com");
        Client client = new Client(config);

        // 2. Upload the file and preview estimate
        File file = new File("/path/to/document.docx");
        InputStream fileStream = new FileInputStream(file);

        UploadTranslationFileAdvanceRequest uploadRequest =
                new UploadTranslationFileAdvanceRequest()
                        .setFileObject(fileStream)
                        .setFileName(file.getName());
        // Member accounts must set the API Key
        // uploadRequest.setAPIKey("your-api-key");

        RuntimeOptions runtimeOptions = new RuntimeOptions()
                .setReadTimeout(120000); // 120 seconds for large files
        UploadTranslationFileResponse uploadResponse =
                client.uploadTranslationFileAdvance(uploadRequest, runtimeOptions);

        String taskId = uploadResponse.getBody().getData().getTaskId();
        System.out.println("TaskId: " + taskId);
        System.out.println("Estimated Credits: " + uploadResponse.getBody().getData().getEstimatedCostCredits());

        // 3. Submit the translation task
        SubmitTranslationTaskRequest.SubmitTranslationTaskRequestConfig translateConfig =
                new SubmitTranslationTaskRequest.SubmitTranslationTaskRequestConfig()
                        .setSourceLanguage(uploadResponse.getBody().getData().getDetectedLang())
                        .setTargetLanguage("en")
                        .setFont("Calibri");

        // Custom terms (optional)
        List<SubmitTranslationTaskRequest.SubmitTranslationTaskRequestCustomTerms> customTerms = new ArrayList<>();
        customTerms.add(new SubmitTranslationTaskRequest.SubmitTranslationTaskRequestCustomTerms()
                .setSourceTerm("人工智能")
                .setTargetTerm("Artificial Intelligence"));

        SubmitTranslationTaskRequest submitRequest = new SubmitTranslationTaskRequest()
                .setTaskId(taskId)
                .setConfig(translateConfig)
                .setCustomTerms(customTerms);

        SubmitTranslationTaskResponse submitResponse = client.submitTranslationTask(submitRequest);
        System.out.println("Status: " + submitResponse.getBody().getData().getStatus());

        // 4. Poll task progress (with timeout)
        String status;
        long startTime = System.currentTimeMillis();
        long timeoutMs = 3600_000; // 1 hour timeout
        do {
            Thread.sleep(5000);
            if (System.currentTimeMillis() - startTime > timeoutMs) {
                System.err.println("Polling timed out after 1 hour");
                return;
            }
            GetTranslationTaskRequest getRequest = new GetTranslationTaskRequest()
                    .setTaskId(taskId);
            GetTranslationTaskResponse getResponse = client.getTranslationTask(getRequest);
            status = getResponse.getBody().getData().getStatus();
            System.out.println("Progress: " + getResponse.getBody().getData().getProgress() + "%, Status: " + status);
        } while ("PENDING".equals(status) || "PROCESSING".equals(status));

        // 5. Download the translated file
        if ("COMPLETED".equals(status)) {
            GetTranslatedFileUrlRequest downloadRequest = new GetTranslatedFileUrlRequest()
                    .setTaskId(taskId);
            GetTranslatedFileUrlResponse downloadResponse = client.getTranslatedFileUrl(downloadRequest);
            System.out.println("Download URL: " + downloadResponse.getBody().getData().getDownloadUrl());
        } else if ("FAILED".equals(status)) {
            System.err.println("Translation failed");
        }
    }
}

Python

import time
from alibabacloud_realtranslationagent20260622.client import Client
from alibabacloud_realtranslationagent20260622.models import (
    UploadTranslationFileAdvanceRequest,
    SubmitTranslationTaskRequest,
    SubmitTranslationTaskRequestConfig,
    SubmitTranslationTaskRequestCustomTerms,
    GetTranslationTaskRequest,
    GetTranslatedFileUrlRequest,
)
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# 1. Initialize the client
config = Config(
    access_key_id="your-access-key-id",
    access_key_secret="your-access-key-secret",
    endpoint="realtranslationagent.aliyuncs.com",
)
client = Client(config)

# 2. Upload the file and preview estimate
with open("/path/to/document.docx", "rb") as f:
    upload_request = UploadTranslationFileAdvanceRequest(
        file_object=f,
        file_name="document.docx",
    )
    # Member accounts must set the API Key
    # upload_request.api_key = "your-api-key"
    runtime_options = RuntimeOptions(read_timeout=120000)  # 120 seconds for large files
    upload_response = client.upload_translation_file_advance(upload_request, runtime_options)

task_id = upload_response.body.data.task_id
print(f"TaskId: {task_id}")
print(f"Estimated Credits: {upload_response.body.data.estimated_cost_credits}")

# 3. Submit the translation task
translate_config = SubmitTranslationTaskRequestConfig(
    source_language=upload_response.body.data.detected_lang,
    target_language="en",
    font="Calibri",
)

custom_terms = [
    SubmitTranslationTaskRequestCustomTerms(
        source_term="人工智能",
        target_term="Artificial Intelligence",
    ),
]

submit_request = SubmitTranslationTaskRequest(
    task_id=task_id,
    config=translate_config,
    custom_terms=custom_terms,
)
submit_response = client.submit_translation_task(submit_request)
print(f"Status: {submit_response.body.data.status}")

# 4. Poll task progress (with timeout)
timeout_seconds = 3600  # 1 hour timeout
start_time = time.time()
while True:
    time.sleep(5)
    if time.time() - start_time > timeout_seconds:
        print("Polling timed out after 1 hour")
        break
    get_request = GetTranslationTaskRequest(task_id=task_id)
    get_response = client.get_translation_task(get_request)
    status = get_response.body.data.status
    print(f"Progress: {get_response.body.data.progress}%, Status: {status}")
    if status not in ("PENDING", "PROCESSING"):
        break

# 5. Download the translated file
if status == "COMPLETED":
    download_request = GetTranslatedFileUrlRequest(task_id=task_id)
    download_response = client.get_translated_file_url(download_request)
    print(f"Download URL: {download_response.body.data.download_url}")
elif status == "FAILED":
    print("Translation failed")

Node.js

import Client from '@alicloud/realtranslationagent20260622';
import { Config } from '@alicloud/openapi-client';
import { RuntimeOptions } from '@alicloud/tea-util';
import {
    UploadTranslationFileAdvanceRequest,
    SubmitTranslationTaskRequest,
    SubmitTranslationTaskRequestConfig,
    SubmitTranslationTaskRequestCustomTerms,
    GetTranslationTaskRequest,
    GetTranslatedFileUrlRequest,
} from '@alicloud/realtranslationagent20260622';
import * as fs from 'fs';

// 1. Initialize the client
const config = new Config({
    accessKeyId: 'your-access-key-id',
    accessKeySecret: 'your-access-key-secret',
    endpoint: 'realtranslationagent.aliyuncs.com',
});
const client = new Client(config);

// 2. Upload the file and preview estimate
const fileStream = fs.createReadStream('/path/to/document.docx');
const uploadRequest = new UploadTranslationFileAdvanceRequest({
    fileObject: fileStream,
    fileName: 'document.docx',
});
// Member accounts must set the API Key
// uploadRequest.apiKey = 'your-api-key';

const runtimeOptions = new RuntimeOptions({ readTimeout: 120000 }); // 120 seconds for large files
const uploadResponse = await client.uploadTranslationFileAdvance(uploadRequest, runtimeOptions);

const taskId = uploadResponse.body.data.taskId;
console.log('TaskId:', taskId);
console.log('Estimated Credits:', uploadResponse.body.data.estimatedCostCredits);

// 3. Submit the translation task
const translateConfig = new SubmitTranslationTaskRequestConfig({
    sourceLanguage: uploadResponse.body.data.detectedLang,
    targetLanguage: 'en',
    font: 'Calibri',
});

const customTerms = [
    new SubmitTranslationTaskRequestCustomTerms({
        sourceTerm: '人工智能',
        targetTerm: 'Artificial Intelligence',
    }),
];

const submitRequest = new SubmitTranslationTaskRequest({
    taskId,
    config: translateConfig,
    customTerms,
});
const submitResponse = await client.submitTranslationTask(submitRequest);
console.log('Status:', submitResponse.body.data.status);

// 4. Poll task progress (with timeout)
const timeoutMs = 3600_000; // 1 hour timeout
const startTime = Date.now();
let status;
do {
    await new Promise((resolve) => setTimeout(resolve, 5000));
    if (Date.now() - startTime > timeoutMs) {
        console.error('Polling timed out after 1 hour');
        break;
    }
    const getRequest = new GetTranslationTaskRequest({ taskId });
    const getResponse = await client.getTranslationTask(getRequest);
    status = getResponse.body.data.status;
    console.log(`Progress: ${getResponse.body.data.progress}%, Status: ${status}`);
} while (status === 'PENDING' || status === 'PROCESSING');

// 5. Download the translated file
if (status === 'COMPLETED') {
    const downloadRequest = new GetTranslatedFileUrlRequest({ taskId });
    const downloadResponse = await client.getTranslatedFileUrl(downloadRequest);
    console.log('Download URL:', downloadResponse.body.data.downloadUrl);
} else if (status === 'FAILED') {
    console.error('Translation failed');
}

Error handling

Real Translation Buddy OpenAPI returns errors through two distinct channels. Your code must handle both:

  • Business errors — HTTP 200 with Success: false in the response body, plus Code and Message fields (e.g., Task.NotFound, Credits.NotEnough).

  • Gateway/auth errors — HTTP 4xx thrown as SDK exceptions (e.g., InvalidAccessKeyId.NotFound, SignatureDoesNotMatch, Throttling).

For a complete list of error codes, see Error Code Reference.

Java

try {
    GetTranslationTaskRequest request = new GetTranslationTaskRequest()
            .setTaskId(taskId);
    GetTranslationTaskResponse response = client.getTranslationTask(request);

    // Check business-level errors (HTTP 200 but Success=false)
    if (!response.getBody().getSuccess()) {
        System.err.println("Business error: " + response.getBody().getCode()
                + " - " + response.getBody().getMessage());
        return;
    }

    // Process successful response
    String status = response.getBody().getData().getStatus();
    System.out.println("Status: " + status);
} catch (TeaException e) {
    // Gateway/auth errors (HTTP 4xx)
    System.err.println("Gateway error: " + e.getCode() + " - " + e.getMessage());
} catch (Exception e) {
    System.err.println("Unexpected error: " + e.getMessage());
}

Python

from Tea.exceptions import TeaException

try:
    request = GetTranslationTaskRequest(task_id=task_id)
    response = client.get_translation_task(request)

    # Check business-level errors (HTTP 200 but Success=False)
    if not response.body.success:
        print(f"Business error: {response.body.code} - {response.body.message}")
    else:
        status = response.body.data.status
        print(f"Status: {status}")
except TeaException as e:
    # Gateway/auth errors (HTTP 4xx)
    print(f"Gateway error: {e.code} - {e.message}")
except Exception as e:
    print(f"Unexpected error: {e}")

Node.js

try {
    const request = new GetTranslationTaskRequest({ taskId });
    const response = await client.getTranslationTask(request);

    // Check business-level errors (HTTP 200 but Success=false)
    if (!response.body.success) {
        console.error(`Business error: ${response.body.code} - ${response.body.message}`);
    } else {
        console.log('Status:', response.body.data.status);
    }
} catch (err) {
    // Gateway/auth errors (HTTP 4xx) or unexpected errors
    if (err.code) {
        console.error(`Gateway error: ${err.code} - ${err.message}`);
    } else {
        console.error('Unexpected error:', err.message);
    }
}