LLM Translation APIs: Engineering Practices for Cross-Border Multilingual Workflows
Learn how to evaluate and integrate LLM translation APIs for cross-border business workflows. This article covers requirements analysis, API selection, token-based cost estimation, service architecture, and Python implementation patterns for terminology control, placeholder protection, retries, and concurrent document translation.
1. Define the Translation Requirements
Cross-border businesses handle many types of text, including business emails, product descriptions, quotations, contract clauses, shipping documents, support tickets, and instant messages. Each has different translation requirements. Contract clauses require precise, unambiguous wording. Product descriptions need accurate specifications and natural language. Instant messages prioritize low latency and conversational phrasing.
Before implementing a translation service, assess requirements across three dimensions:
- Text type: Determines the writing style, terminology density, and formatting constraints.
- Request mode: Distinguish offline batch processing, such as translating entire documents, from real-time interactions, such as customer support conversations. These workloads have different latency and throughput requirements.
- Language mix: Translation quality can vary substantially between high-resource and low-resource languages, so evaluate them separately.
Establishing the relative importance of these dimensions provides a basis for API selection and budgeting.
2. Evaluate LLM Translation APIs
Compare APIs across at least the following six dimensions, with measurable acceptance criteria for each:
- Translation quality: Use your own datasets to test domain terminology consistency, natural phrasing, and preservation of proper names.
- Language coverage: Confirm that the API reliably supports your target languages, and test low-resource languages separately.
- Format preservation: Verify that numbering, units, dates, code, placeholders, and other structured content remain intact.
- Latency and throughput: Measure time to first token and total response time. Observe rate-limit behavior under concurrent load.
- Cost structure: Many APIs charge separately for input and output tokens. Output rates are often higher, so estimate the cost of long translations explicitly.
- Integration and compliance: Assess authentication methods, data retention policies, logging scope, and applicable requirements for cross-border data transfers.
3. Estimate Translation Costs
For token-based pricing, estimate the cost of a single request as follows:
Request cost =(input tokens / 1,000,000 × input price per million tokens)+ (output tokens / 1,000,000 × output price per million tokens)
Keep the following considerations in mind:
- Token counts depend on the language and tokenizer. Chinese and English texts with the same character count do not necessarily consume the same number of tokens. Before deployment, collect real samples and use the API’s reported usage fields rather than relying solely on rough estimates.
- System prompts, including glossaries and formatting instructions, contribute to input tokens on every request. Longer glossaries increase fixed overhead, creating a trade-off between terminology coverage and cost.
- Translations are often similar in length to the source, but some target languages produce substantially longer output. Include a margin in the budget.
For example, suppose a document requires approximately 30,000 input tokens and 35,000 output tokens. Assume an input price of CNY 10 per million tokens and an output price of CNY 30 per million tokens. These are hypothetical rates for illustration only; use the provider’s actual pricing.
The estimated document cost is:
(30,000 / 1,000,000 × CNY 10)+ (35,000 / 1,000,000 × CNY 30)= CNY 1.35
Use the same calculation to estimate monthly batch-processing costs.
4. Design the Translation Service Architecture
A reliable translation service typically includes these stages:
- Preprocessing: Clean the text, split it into paragraphs or sentences, and identify placeholders and content that should not be translated.
- Prompt assembly: Add the target language, style requirements, and glossary.
- Model invocation: Use a request layer with timeouts, retries, and rate limiting.
- Postprocessing: Restore placeholders, validate numbers and units, and check terminology consistency.
- Caching and storage: Use hash-based caching for identical text to avoid repeated charges.
- Monitoring and alerts: Track request volume, failure rate, latency, and cost. Notify the responsible team when thresholds are exceeded.
The following example demonstrates the core logic for preprocessing, prompt assembly, request retries, and concurrent segment translation. It assumes a response structure similar to a common chat completion format. Follow the relevant API documentation when integrating a specific service.
The endpoint and API key are read from environment variables rather than embedded in the code. The glossary retains Chinese source terms because this example translates Chinese business text.
import jsonimport osimport reimport timeimport urllib.requestimport urllib.errorfrom concurrent.futures import ThreadPoolExecutorAPI_BASE = os.environ["TRANSLATE_API_BASE"]API_KEY = os.environ["TRANSLATE_API_KEY"]MODEL = os.environ.get("TRANSLATE_MODEL", "translation-model")# Glossary: keep business terminology consistent throughout the document.GLOSSARY = {"发货": "ship", "信用证": "letter of credit", "验货": "inspection"}# Content to preserve exactly: template variables, quantities, and units.PROTECT_RE = re.compile(r"\{\{[^}]+\}\}|\d+(?:\.\d+)?\s?(?:kg|cm|mm|pcs)")def protect(text):"""Replace protected spans with placeholders and return their mapping."""mapping = {}def repl(match):key = f"__PH{len(mapping)}__"mapping[key] = match.group(0)return keyreturn PROTECT_RE.sub(repl, text), mappingdef restore(text, mapping):"""Restore placeholders in the translation to their original values."""for key, value in mapping.items():text = text.replace(key, value)return textdef build_messages(text, target_lang):"""Build a prompt with the target language, placeholder rules, and glossary."""glossary = "\n".join(f"{src} -> {dst}" for src, dst in GLOSSARY.items())system = (f"You are a professional translator for international trade. "f"The target language is {target_lang}. ""Preserve placeholders in the form __PH<number>__ exactly; ""do not translate or modify them. "f"Use the following terminology exactly as specified:\n{glossary}")return [{"role": "system", "content": system},{"role": "user", "content": text},]def call_model(messages, max_retries=3):"""Call the API, retrying rate-limit and server errors with exponential backoff."""payload = {"model": MODEL, "messages": messages, "temperature": 0.2}body = json.dumps(payload).encode("utf-8")headers = {"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json",}for attempt in range(max_retries):req = urllib.request.Request(API_BASE, data=body, headers=headers, method="POST")try:with urllib.request.urlopen(req, timeout=30) as resp:data = json.loads(resp.read().decode("utf-8"))return data["choices"][0]["message"]["content"]except urllib.error.HTTPError as err:if err.code == 429 or err.code >= 500:time.sleep(2 ** attempt)continueraiseraise RuntimeError("Translation request failed after retries")def split_segments(text, max_chars=800):"""Split text at paragraph boundaries to limit request length."""segments, current = [], ""for para in text.split("\n"):if current and len(current) + len(para) > max_chars:segments.append(current)current = ""current += para + "\n"if current.strip():segments.append(current)return segmentsdef translate_one(segment, target_lang):masked, mapping = protect(segment)result = call_model(build_messages(masked, target_lang))return restore(result, mapping)def translate_document(text, target_lang, workers=4):"""Translate segments concurrently while preserving their original order.Set concurrency according to the provider's rate limits."""segments = split_segments(text)with ThreadPoolExecutor(max_workers=workers) as pool:results = list(pool.map(lambda s: translate_one(s, target_lang), segments))return "".join(results)
Several implementation details require attention:
split_segmentssplits only at paragraph boundaries. An unusually long paragraph still needs sentence-level splitting; otherwise, it may exceed the API’s per-request input limit.- Expand the placeholder rules to match your business content. Order numbers, product codes, and URLs should also be protected.
- Keep concurrency below the provider’s rate-limit thresholds. Excessive concurrency can trigger retries, increase total processing time, and reduce effective throughput.
5. Check Terminology Consistency and Translation Accuracy
Common machine translation problems include using different translations for the same term across paragraphs and altering numbers or units. Add automated checks during postprocessing:
- Terminology validation: Check whether each glossary source term appears in the original text. If it does, verify that the translation uses the specified equivalent.
- Number and unit validation: Check that numbers and units are preserved accurately in the translated output.
