Repository navigation
Expand file tree
/
Copy pathexample-translation.ts
More file actions
261 lines (220 loc) · 9.25 KB
/
Copy pathexample-translation.ts
File metadata and controls
261 lines (220 loc) · 9.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#!/usr/bin/env node
/**
* SAP AI Provider - Translation Example
*
* This example demonstrates input and output translation using the
* SAP AI Core Orchestration API's translation module.
*
* Translation allows you to:
* - **Input Translation**: Translate user queries from one language to another
* before sending to the LLM (e.g., German → English)
* - **Output Translation**: Translate LLM responses back to the user's language
* (e.g., English → German)
*
* This is particularly useful for:
* - Supporting users in multiple languages with a single English-based LLM
* - Ensuring consistent quality by using the LLM in its strongest language
* - Building multilingual applications without managing separate models
*
* Authentication:
* - On SAP BTP: Automatically uses service binding (VCAP_SERVICES)
* - Locally: Set AICORE_SERVICE_KEY environment variable with your service key JSON
*/
// Load environment variables
import "dotenv/config";
import { APICallError, LoadAPIKeyError, NoSuchModelError } from "@ai-sdk/provider";
import { generateText } from "ai";
// In an application, import from the published V4 entrypoint:
// import { createSAPAIProvider, buildTranslationConfig } from "@jerome-benoit/sap-ai-provider/v4";
import { buildTranslationConfig, createSAPAIProvider } from "../src/index-v4";
import { parseSAPErrorResponseBody } from "./parse-sap-error-response-body.js";
/** Configures SAP document translation independently of the underlying model. */
async function translationExample() {
console.log("🌐 SAP AI Translation Example\n");
// Verify AICORE_SERVICE_KEY is set for local development
if (!process.env.AICORE_SERVICE_KEY && !process.env.VCAP_SERVICES) {
console.warn("⚠️ Warning: AICORE_SERVICE_KEY environment variable not set.");
console.warn(" Set it in your .env file or environment for local development.\n");
}
try {
// Example 1: Input Translation Only
// User asks in German, LLM processes in English
console.log("================================");
console.log("📝 Example 1: Input Translation (German → English)");
console.log("================================\n");
const inputTranslationConfig = buildTranslationConfig("input", {
sourceLanguage: "de", // German input
targetLanguage: "en", // Translate to English for LLM
});
const providerInputTranslation = createSAPAIProvider({
defaultSettings: {
translation: {
input: inputTranslationConfig,
},
},
});
const modelInputTranslation = providerInputTranslation("gpt-4.1");
const germanQuery = "Was sind die Hauptvorteile von SAP AI Core?";
console.log(`🇩🇪 German Query: ${germanQuery}\n`);
const { text: inputTranslatedText } = await generateText({
messages: [
{
content: germanQuery,
role: "user",
},
],
model: modelInputTranslation,
});
console.log("🤖 Response (in English):", inputTranslatedText);
console.log("\n📌 Note: The query was automatically translated from German to English");
console.log(" before being sent to the LLM.");
// Example 2: Output Translation Only
// User asks in English, LLM responds in German
console.log("\n================================");
console.log("📝 Example 2: Output Translation (English → German)");
console.log("================================\n");
const outputTranslationConfig = buildTranslationConfig("output", {
targetLanguage: "de", // Translate response to German
});
const providerOutputTranslation = createSAPAIProvider({
defaultSettings: {
translation: {
output: outputTranslationConfig,
},
},
});
const modelOutputTranslation = providerOutputTranslation("gpt-4.1");
const englishQuery = "What are the main benefits of SAP AI Core?";
console.log(`🇬🇧 English Query: ${englishQuery}\n`);
const { text: outputTranslatedText } = await generateText({
messages: [
{
content: englishQuery,
role: "user",
},
],
model: modelOutputTranslation,
});
console.log("🤖 Response (in German):", outputTranslatedText);
console.log("\n📌 Note: The LLM processed the query in English and the response");
console.log(" was automatically translated to German.");
// Example 3: Bidirectional Translation
// User asks in French, LLM processes in English, responds in French
console.log("\n================================");
console.log("📝 Example 3: Bidirectional Translation (French ↔ English)");
console.log("================================\n");
const bidirectionalTranslationConfig = {
input: buildTranslationConfig("input", {
sourceLanguage: "fr",
targetLanguage: "en",
}),
output: buildTranslationConfig("output", {
targetLanguage: "fr",
}),
};
const providerBidirectional = createSAPAIProvider({
defaultSettings: {
translation: bidirectionalTranslationConfig,
},
});
const modelBidirectional = providerBidirectional("gpt-4.1");
const frenchQuery = "Quels sont les principaux avantages de SAP AI Core?";
console.log(`🇫🇷 French Query: ${frenchQuery}\n`);
const { text: bidirectionalText } = await generateText({
messages: [
{
content: frenchQuery,
role: "user",
},
],
model: modelBidirectional,
});
console.log("🤖 Response (in French):", bidirectionalText);
console.log("\n📌 Note: The query was translated from French to English,");
console.log(
" processed by the LLM in English, and the response was translated back to French.",
);
// Example 4: Multilingual Support with Different Languages
console.log("\n================================");
console.log("📝 Example 4: Supporting Multiple Languages");
console.log("================================\n");
const languages = [
{ code: "es", name: "Spanish", query: "¿Qué es SAP AI Core?" },
{ code: "it", name: "Italian", query: "Cos'è SAP AI Core?" },
{ code: "ja", name: "Japanese", query: "SAP AI Coreとは何ですか?" },
];
for (const lang of languages) {
console.log(`\n${lang.name} (${lang.code}):`);
console.log(` Query: ${lang.query}`);
const langConfig = {
input: buildTranslationConfig("input", {
sourceLanguage: lang.code,
targetLanguage: "en",
}),
output: buildTranslationConfig("output", {
targetLanguage: lang.code,
}),
};
const langProvider = createSAPAIProvider({
defaultSettings: {
translation: langConfig,
},
});
const langModel = langProvider("gpt-4.1");
const { text: langText } = await generateText({
messages: [
{
content: lang.query,
role: "user",
},
],
model: langModel,
});
console.log(` Response: ${langText}`);
}
console.log("\n✅ Translation example completed!");
console.log("\n💡 Key Takeaways:");
console.log(" - Input translation: Translate user queries to LLM's language");
console.log(" - Output translation: Translate responses to user's language");
console.log(" - Bidirectional: Combine both for seamless multilingual UX");
console.log(
" - Use language identifiers supported by SAP Document Translation (e.g., en-US).",
);
console.log(" - No source language needed for output translation (auto-detected)");
} catch (error: unknown) {
process.exitCode = 1;
if (error instanceof LoadAPIKeyError) {
console.error("❌ Authentication Error:", error.name);
} else if (error instanceof NoSuchModelError) {
console.error("❌ Model Not Found:", error.modelId);
} else if (error instanceof APICallError) {
console.error("❌ API Call Error:", error.statusCode, error.name);
// Parse SAP-specific metadata
const sapError = parseSAPErrorResponseBody(error.responseBody);
if (sapError?.error.request_id) {
console.error(" SAP Request ID:", sapError.error.request_id);
}
// Common errors
if (error.statusCode === 400) {
console.error("\n💡 HTTP 400: inspect the request and translation configuration.");
console.error(
" Check SAP Document Translation language identifiers, including locale tags.",
);
}
} else {
const errorName = error instanceof Error ? error.name : "Unknown error";
console.error("❌ Example failed:", errorName);
}
console.error("\n💡 Troubleshooting tips:");
console.error(" - Ensure AICORE_SERVICE_KEY is set with valid credentials");
console.error(" - Check that your SAP AI Core instance is accessible");
console.error(" - Verify translation is available in your SAP orchestration setup");
console.error(" - Use supported SAP Document Translation language identifiers");
console.error(" - Check SAP AI Core documentation for supported languages");
}
}
translationExample().catch((error: unknown) => {
process.exitCode = 1;
console.error("Example failed:", error instanceof Error ? error.name : "Unknown error");
});
export { translationExample };