Skip to main content

AI Translation Development Integration Guide

1. Preparation before integration

1.1 Prerequisites

  • Registered Player Network console and finished business project creation.
  • If using SDK integration, the client Player Network SDK version must be 1.32 or above.

1.2 Choosing integration method

Integration MethodApplication scenariosIntegration features
SDK Integration (Recommended)The business has integrated the Player Network SDK, and the client can directly call SDK capabilities.Short development cycle, suitable for real-time in-game features.
API IntegrationOnly integrate the AI Translation Service, or invoke centrally via the game backend.Facilitates unified authentication, rate limiting, log auditing, and business encapsulation.

2. Management Console Operation

  1. When you first enter the Translation Content Management, click "Try it for free now" to complete AI translation feature initialization.

AI Translation Feature Initialization Entry

  1. Click the upper right corner "Scene Switch" to obtain the gameCode corresponding to this business scenario.It is recommended to always include the gameCode when making SDK/API calls.

Retrieve gameCode via Scene Switch

  1. When accessing via API, go to "Project Information" and select "AI Translation". Fill in the game backend outbound IP in "IP Whitelist" and click save.

AI Translation API IP Whitelist Configuration

3. Backend API Integration

3.1 Integration Flow

  1. The client or business service submits the text to be translated, along with the source language, target language, business scenario, and other relevant information to the game backend.
  2. The game backend uses appId + secret to generate a JWT Token and calls the AI Translation API.
  3. The AI Translation Service returns retCode, message, and result; the backend sends these to the client or writes them to the business system as required.
  4. Backend logs key fields like traceId, openId, gameCode, srcLang, targetLang, retCode for troubleshooting.

3.2 API Information

When calling AI Translation API from backend, select the appropriate service domain name based on the deployment environment and concatenate with /api/v1/translator as the interface path.

EnvironmentBackend Domain NameFull Call Address
test environmenthttp://translator.ai-test.levelinfinite.comPOST http://translator.ai-test.levelinfinite.com/api/v1/translator
Production environmenthttp://translator.ai.levelinfinite.comPOST http://translator.ai.levelinfinite.com/api/v1/translator
ProjectDescription
Interface PathPOST \<API domain>/api/v1/translator
Content-Typeapplication/json
AuthorizationBearer \<token>
Authentication MethodJWT, signature algorithm HS256; payload.data.account must equal the request body appId; payload.exp is the Unix expiration time in seconds.
Feature DescriptionSupports batch text translation, automatic source language detection, terminology/phrase locking, translation caching, and multi-strategy translation fallback.

3.3 Request Parameters

ParameterTypeRequiredDescription
openIdstringYesUser ID, identifies the specific user.
appIdstringYesThe appId assigned by the admin must be consistent with payload.data.account in the JWT.
srcLangstringYesSource language code; use auto if uncertain.
targetLangstringYesTarget language code such as zh, en, ja, ko, ru.
gameCodestringNo, it is recommended to passBusiness scenario code; if empty, the default gameCode of appId will be used; it is recommended to apply separately for different scenarios.
text[]stringYesList of texts to translate, up to 5 items, total tokens must not exceed 4096.
contextjson objectNoTranslation context, includes topic, pastConversation, remark.
traceIdstringNo, recommendedUnique request ID, used for request tracing.
noCacheboolNoCache bypass: false uses cache, true does not use cache; default is false.
extInfostringNoExtension field, JSON string, for future expansion.

context parameter

ParameterTypeRequiredDescription
topicstringNoTopic/scene, e.g. "game chat", "event announcement", "esports commentary".
pastConversationstringNoHistorical conversation context, improves consistency of conversation translation.
remarkstringNoAdditional description, e.g. proper nouns, role names, tone requirements.

3.4 JWT Token Generation Requirements

  • Use secret assigned by admin as HS256 signature key.
  • payload must include data.account, value is appId.
  • payload must include exp, value is Unix seconds expiration.
  • Request header uses Authorization: Bearer \<token>.
  • Request body appId must match data.account in token.
JWT payload 示例
{
"exp": 1710000000,
"data": {
"account": "<appId>"
}
}

3.5 Request Example

POST /api/v1/translator HTTP/1.1
Content-Type: application/json
Authorization: Bearer <token>

{
"openId": "test-user-001",
"appId": "<app-id>",
"srcLang": "auto",
"targetLang": "en",
"gameCode": "<game-code>",
"text": ["Cosmodrone's heavy armored soldier"],
"context": {
"topic": "game chat",
"pastConversation": "",
"remark": ""
},
"traceId": "translator-20260701-0001",
"noCache": false,
"extInfo": ""
}

3.6 Response Handling

Response FieldTypeDescriptionHandling Suggestion
retCodestringReturn code, "0" indicates success.When not 0, return a business fallback prompt based on error type and record the traceId.
messagestringReturn message.For log positioning, frontend display needs to be converted to business-friendly text.
result[]ContentThe list of translations results is consistent with the request text order.Map back to original text by index.
debugInfojson objectNot returned by default, usually null.Generally not passed through to the client.

Content Fields

FieldTypeDescription
textstringOriginal text.
outputstringTranslation result.
idstringContent ID, calculated as MD5 of appId + srcLang + targetLang + text.
成功响应示例
{
"retCode": "0",
"message": "Success",
"result": [
{
"text": "Cosmodrone's heavy armored soldier",
"output": "Cosmodrone's heavy armored soldier",
"id": "f009a3089f293939c0f01f36c0f047e2"
}
],
"debugInfo": null
}

3.7 Error Code and Backend Handling Suggestions

retCodeTypeCommon causesHandling Suggestion
0SuccessCall succeeded.Return result.output.
1service codec UnmarshalParameter type error, e.g. string passed as int.Check request JSON serialization and field types.
1001ParamsErrorappId does not exist, unsupported language, text is empty or exceeds batch limit, traceId too long.Validate parameters; log errors and traceId.
1002ServiceInternalErrorInternal Service Error.Retry briefly; if multiple failures occur, contact PNT support and provide the traceId.
1003PermissionErrorToken missing, expired, signature error, or token appId is inconsistent with the request body.Regenerate token; check appId/secret.
1007rate limit reachedQPM or daily PV reached the hard rate limit.Frontend prompts retry later; backend circuit breaks or degrades; contact Admin to adjust quota.
Phrase lock instructions

Original text can be marked as not to be translated using the <span class='notranslate'>{word}</span> tag.The caller needs to handle any <span class='notranslate'></span> tags that may be returned in the translation to avoid displaying the tags directly to players.

4. Client SDK Integration

Version requirement

SDK integration for AI translation requires Player Network SDK version 1.32 or above.Relative capabilities are not supported in version below 1.32 and require SDK upgrades.

4.1 Integration Flow

  1. Ensure the client has completed Player Network SDK initialization and user login, and can obtain login state information such as openId / token.
  2. Obtain gameCode from console or backend configuration; if distributed by backend, synchronize configuration at client startup.
  3. Construct INTLTranslatorReq request struct, fill source language, target language, texts to translate, context, and traceId.
  4. Call translation interface encapsulated by SDK to submit request.Actual method name is subject to the SDK version documentation.
  5. Read translatorResp from INTLTranslatorResult callback and parse translator_rsp.result[].output.
  6. Fallback display and report traceId for non-zero retCode or SDK base error codes.

4.2 INTLTranslatorReq Field Description

FieldTypeRequiredDescriptionFilling Suggestion
SrcLangstringYesOriginal language, default auto.If player input language is unclear, pass auto.
TargetLangstringYesTarget language.Recommended: use player current UI language or recipient language.
TranslateTextsstringYesTranslation content, format is JSON array string, up to 5 groups.Example: ["hello", "world"]; note not an array object.
TopicstringNoTranslation text background information.Can fill game_chat, notice, support_ticket, etc.
PastConversationstringNoHistorical conversation content.Used for continuous translation of the context of the conversation.
RemarkstringNoOther supplementary information.Can fill in the role name, equipment name, terminology description.
NoCacheboolNoWhether to disable cache, default false.For real-time chat generally use false; for special dynamic text can set true.
GameCodestringNo, it is recommended to passgameCode assigned by AI Translation Service.Use value retrieved via admin console scene switching.
ExtInfostringNoExtension JSON field, note: it is a JSON string.For example {"scene":"chat"}.
TraceIdstringNo, it is recommended to passUnique request ID, used for request-response association.Recommended to generate UUID by client or backend.
客户端请求结构示例(伪代码,方法名以 SDK 实际版本为准)
INTLTranslatorReq req;
req.SrcLang = "auto";
req.TargetLang = "en";
req.TranslateTexts = "[\"Cosmodrone's heavy armored soldier\"]";
req.Topic = "game_chat";
req.PastConversation = "";
req.Remark = "";
req.NoCache = false;
req.GameCode = "<game-code>";
req.ExtInfo = "";
req.TraceId = "client-trace-001";

// SDK.Translate(req, OnTranslatorResult);

4.3 INTLTranslatorResult Callback Handling

  • Translation results are returned in translatorResp; the game side needs to parse them itself.
  • First determine SDK base result ret / ret_code, then parse translator_rsp.retCode.
  • When translator_rsp.retCode is "0", get translation from translator_rsp.result[].output.
  • translator_rsp.result and text order in request TranslateTexts correspond one-to-one.
translatorResp 核心结构示例
{
"ret": 0,
"msg": "success",
"translator_rsp": {
"retCode": "0",
"message": "Success",
"traceId": "trace",
"result": [
{
"text": "Original Text",
"output": "Translated Text",
"id": "c5b2802a287f58c9ce250f8c77fc6029"
}
]
},
"asr_rsp": ""
}

5. Joint debugging & acceptance

5.1 Acceptance Checklist

Checklist ItemsAcceptance CriteriaTroubleshooting Fields
Feature InitializationAdmin console has completed AI translation initialization.Project ID, appId
gameCodegameCode passed through SDK/API is consistent with admin console scenario.gameCode, traceId
WhitelistBackend outbound IP added to AI translation API whitelist.Outbound IP, request time
JWT AuthenticationAuthorization: Bearer \<token> passes authentication.appId, exp, traceId
Parameter ValidationFields such as openId, srcLang, targetLang, text meet requirements.Request body, retCode, message
Batch LimitUp to 5 texts per request, total tokens not exceeding 4096.text length, retCode
Response Mappingresult order matches request text order; client displays output.id, text, output
Error FallbackErrors like 1001/1003/1007 are correctly prompted and reported.retCode, message, traceId

5.2 Go-live Confirmation

  • Production domain, whitelist, and rate limit configuration confirmed.
  • Backend token expiration is reasonable and supports auto-refresh.
  • Do not log secret, full token, or user sensitive text.
  • Client provides fallback content for translation failures.
  • Critical error codes and traceId are integrated with monitoring and reporting.

6. Common Issues & Troubleshooting Suggestions

QuestionPossible CauseSolution
AI Translation returns PermissionError / 1003Token missing, expired, signature error, or request body appId does not match token account.Regenerate token; check secret; ensure Authorization: Bearer \<token> format.
AI Translation returns ParamsError / 1001appId does not exist, unsupported language, text is empty or exceeds limit.Check appId, srcLang, targetLang, text quantity and length; keep traceId for troubleshooting.
SDK callback prompts Invalid param, openid or token emptyThe client is not logged in or did not obtain openId/token from authResult.Log in again; ensure SDK login state is valid before invoking.
SDK callback invalid config / ret 91002Backend configuration missing.Contact Player Network Assistant to supplement configuration.
Rate limit error 1007QPM or daily PV reached hard rate limit.Business side degrades or prompts retry; contact Admin to adjust rate limit configuration.
Common Client Exceptions

Callback returns Invalid param, openid or token empty is usually because openId or token was not passed.Please log in again and obtain the correct openId/token from authResult login state before invoking the interface.

Callback returns "msg":"invalid config", "ret":91002 is usually due to missing backend configuration; contact Player Network Assistant for configuration.

Appendix: Backend Integration Pseudocode

Python 伪代码:生成 JWT 并调用 AI 翻译
import time
import uuid

import jwt
import requests

app_id = "<app-id>"
secret = "<secret>"
api_url = "https://<api-domain>/api/v1/translator"

token = jwt.encode(
{
"data": {"account": app_id},
"exp": int(time.time()) + 300,
},
secret,
algorithm="HS256",
)

body = {
"openId": "test-user-001",
"appId": app_id,
"srcLang": "auto",
"targetLang": "en",
"gameCode": "<game-code>",
"text": ["Cosmodrone's heavy armored soldier"],
"traceId": str(uuid.uuid4()),
"noCache": False,
"extInfo": "",
}

resp = requests.post(
api_url,
json=body,
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
},
)
print(resp.json())