JSON definition · shared/definitions/ai-translation.json
View on GitHub
{
"title": {
"default": "Workshop registration",
"fr": "Inscription à l'atelier"
},
"description": "Choose a session and leave your contact details",
"elements": [
{
"type": "text",
"name": "full_name",
"title": "Full name",
"isRequired": true
},
{
"type": "text",
"name": "email",
"title": "Email address",
"inputType": "email",
"isRequired": true
},
{
"type": "radiogroup",
"name": "session",
"title": "Preferred session",
"isRequired": true,
"choices": [
{
"value": "morning",
"text": "Morning"
},
{
"value": "afternoon",
"text": "Afternoon"
}
]
}
]
}
Client · shared/client/ai-translation.js · sjs:ai-translation.client
View on GitHub
// Return translated strings in the original order, and always finish the callback
creator.onMachineTranslate.add(async (_, options) => {
showError("");
try {
const response = await fetch("/api/translate", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ strings: options.strings, from: options.fromLocale, to: options.toLocale })
});
if (!response.ok) throw await responseError(response, "AI translation failed. Please try again.");
const strings = await response.json();
if (!Array.isArray(strings) || strings.length !== options.strings.length || strings.some(text => typeof text !== "string"))
throw new Error("The translation provider returned an invalid result. Please try again.");
options.callback(strings);
} catch (error) {
options.callback([]);
showError(`${translationError(error)} Existing translations are kept.`);
note(error.message, "error");
}
});
Server · Endpoints/AiTranslation.cs · sjs:ai-translation.server
View on GitHub
// POST /api/translate — strings in, translated strings out (same order); nothing goes to SurveyJS
app.MapPost("/api/translate", async (TranslateRequest body, AiTranslationClient ai, IOptions<SurveyJsOptions> options, CancellationToken aborted) =>
{
if (string.IsNullOrEmpty(options.Value.AiApiKey))
return Results.Json(new { error = "Set AI_API_KEY to enable translation" }, statusCode: 501);
var translated = await ai.TranslateAsync(body.Strings, body.From, body.To, aborted); // any OpenAI-compatible provider: your key, your choice
if (translated is not JsonArray list || list.Count != body.Strings.Count || list.Any(s => s?.GetValueKind() != JsonValueKind.String))
return Results.Json(new { error = "The AI provider returned an unexpected answer" }, statusCode: 502);
return Results.Json(list); // what options.callback() takes
});