@publishpress/potomatic 0.0.0-stage → 1.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,805 @@
1
+ import OpenAI from 'openai';
2
+ import { Provider } from '../base/Provider.js';
3
+ import { DEFAULT_MODEL, FALLBACK_PRICING, KNOWN_MODELS, REASONING_EFFORTS, TRUNCATED_ERROR_CODE, buildRequestParams, getEncodingForModel, reasoningHeadroomTokens } from './modelCapabilities.js';
4
+ import { buildXmlPrompt, parseXmlResponse, buildDictionaryResponse } from '../../utils/xmlTranslation.js';
5
+ import { loadDictionary, findDictionaryMatches } from '../../utils/dictionaryUtils.js';
6
+
7
+ /**
8
+ * OpenAI Provider Implementation.
9
+ *
10
+ * Handles translation using OpenAI's language models (GPT-5, GPT-5.4, etc.).
11
+ * Implements the Provider interface with OpenAI-specific functionality.
12
+ *
13
+ * @since 1.0.0
14
+ */
15
+ export class OpenAIProvider extends Provider {
16
+ /**
17
+ * Creates a new OpenAI Provider instance.
18
+ *
19
+ * @since 1.0.0
20
+ *
21
+ * @param {Object} config - OpenAI provider configuration.
22
+ * @param {Object} logger - Logger instance.
23
+ */
24
+ constructor(config, logger) {
25
+ super(config, logger);
26
+
27
+ this.client = null;
28
+ }
29
+
30
+ /**
31
+ * Initializes the OpenAI provider.
32
+ * Sets up authentication and loads pricing information.
33
+ *
34
+ * @since 1.0.0
35
+ *
36
+ * @throws {Error} If API key is missing or initialization fails.
37
+ *
38
+ * @return {Promise<void>} Resolves when initialization is complete.
39
+ */
40
+ async initialize() {
41
+ if (!this.config.apiKey && !this.config.dryRun) {
42
+ throw new Error('API key is required for non-dry-run mode');
43
+ }
44
+
45
+ if (!this.config.dryRun && this.config.apiKey) {
46
+ this.client = new OpenAI({
47
+ apiKey: this.config.apiKey,
48
+ timeout: this.config.timeout * 1000,
49
+ });
50
+ }
51
+
52
+ await this._loadProviderPricing('openai');
53
+
54
+ this.logger.debug(`OpenAI provider initialized with model: ${this.config.model}`);
55
+ }
56
+
57
+ /**
58
+ * Validates OpenAI provider configuration.
59
+ *
60
+ * @since 1.0.0
61
+ *
62
+ * @param {Object} config - Configuration to validate.
63
+ *
64
+ * @return {Object} Validation result.
65
+ */
66
+ validateConfig(config) {
67
+ const errors = [];
68
+
69
+ if (!config.dryRun && !config.apiKey) {
70
+ errors.push('API key is required (set OPENAI_API_KEY, POTOMATIC_API_KEY, or use --dry-run)');
71
+ }
72
+
73
+ const supportedModels = this.getSupportedModels();
74
+
75
+ if (config.model && !supportedModels.includes(config.model) && !config.allowUnknownModel) {
76
+ errors.push(`Unsupported model: ${config.model}. Supported: ${supportedModels.join(', ')}. Pass --allow-unknown-model to use it anyway.`);
77
+ }
78
+
79
+ if (config.temperature !== undefined && (config.temperature < 0 || config.temperature > 2)) {
80
+ errors.push('Temperature must be between 0.0 and 2.0');
81
+ }
82
+
83
+ if (config.reasoningEffort && !REASONING_EFFORTS.includes(config.reasoningEffort)) {
84
+ errors.push(`Reasoning effort must be one of: ${REASONING_EFFORTS.join(', ')}`);
85
+ }
86
+
87
+ return {
88
+ isValid: errors.length === 0,
89
+ errors,
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Translates a batch of strings using OpenAI's API.
95
+ *
96
+ * @since 1.0.0
97
+ *
98
+ * @param {Array} batch - Array of translation items.
99
+ * @param {string} targetLang - Target language code.
100
+ * @param {string} model - OpenAI model to use.
101
+ * @param {string} systemPrompt - System prompt for translation.
102
+ * @param {number} maxRetries - Maximum retry attempts.
103
+ * @param {number} retryDelayMs - Delay between retries.
104
+ * @param {number} timeout - Request timeout.
105
+ * @param {boolean} isDryRun - Whether this is a dry run.
106
+ * @param {Function} retryProgressCallback - Optional callback for retry progress updates.
107
+ * @param {Object} debugConfig - Optional debug configuration object.
108
+ * @param {number} pluralCount - Number of plural forms for target language.
109
+ *
110
+ * @return {Promise<Object>} Translation result.
111
+ */
112
+ async translateBatch(batch, targetLang, model, systemPrompt, maxRetries, retryDelayMs, timeout, isDryRun, retryProgressCallback = null, debugConfig = null, pluralCount = 1) {
113
+ let dictionaryMatches = [];
114
+
115
+ if (this.config.useDictionary) {
116
+ const dictionary = loadDictionary(this.config.dictionaryPath, targetLang, this.logger);
117
+
118
+ dictionaryMatches = findDictionaryMatches(batch, dictionary);
119
+
120
+ if (dictionaryMatches.length > 0) {
121
+ this.logger.info(`Using dictionary: Found ${dictionaryMatches.length} matching terms for ${targetLang}: ${dictionaryMatches.map((m) => m.source).join(', ')}`);
122
+ } else {
123
+ this.logger.debug(`No dictionary matches found for ${targetLang} in this batch`);
124
+ }
125
+ }
126
+
127
+ const promptResult = buildXmlPrompt(batch, targetLang, pluralCount, dictionaryMatches);
128
+ const xmlPrompt = promptResult.xmlPrompt;
129
+
130
+ const messages = [
131
+ { role: 'system', content: systemPrompt },
132
+ { role: 'user', content: xmlPrompt },
133
+ ];
134
+
135
+ if (dictionaryMatches.length > 0) {
136
+ const dictionaryResponse = buildDictionaryResponse(dictionaryMatches);
137
+
138
+ messages.push({ role: 'assistant', content: dictionaryResponse });
139
+
140
+ const exampleTerms = dictionaryMatches
141
+ .slice(0, 2)
142
+ .map((match) => `"${match.source}" MUST be translated as "${match.target}"`)
143
+ .join(' and ');
144
+
145
+ const instruction = `IMPORTANT: When translating the following strings, you MUST use the exact dictionary translations shown above for any terms that appear in the dictionary. For example, ${exampleTerms}. Use these exact translations, not alternatives. Now translate the actual strings:`;
146
+
147
+ messages.push({
148
+ role: 'user',
149
+ content: instruction,
150
+ });
151
+ }
152
+
153
+ if (isDryRun) {
154
+ return this._handleDryRun(messages, model, batch, pluralCount, promptResult.dictionaryCount);
155
+ }
156
+
157
+ return await this._makeApiCallWithRetries(messages, model, batch, maxRetries, retryDelayMs, retryProgressCallback, debugConfig, pluralCount, promptResult.dictionaryCount);
158
+ }
159
+
160
+ /**
161
+ * Calculates cost based on OpenAI token usage.
162
+ *
163
+ * @since 1.0.0
164
+ *
165
+ * @param {Object} usage - Token usage from OpenAI API response.
166
+ * @param {string} model - Model used.
167
+ *
168
+ * @return {Object} Cost breakdown.
169
+ */
170
+ calculateCost(usage, model) {
171
+ if (!usage || typeof usage !== 'object') {
172
+ return {
173
+ promptCost: 0,
174
+ completionCost: 0,
175
+ totalCost: 0,
176
+ model,
177
+ error: 'Invalid usage data',
178
+ };
179
+ }
180
+
181
+ const { prompt_tokens: promptTokens, completion_tokens: completionTokens, total_tokens: totalTokens } = usage;
182
+
183
+ if (!promptTokens && !completionTokens) {
184
+ return {
185
+ promptCost: 0,
186
+ completionCost: 0,
187
+ totalCost: 0,
188
+ model,
189
+ error: 'No token usage data',
190
+ };
191
+ }
192
+
193
+ const pricingUsed = this.getModelPricing(model);
194
+ const promptCost = (promptTokens / 1000) * pricingUsed.prompt;
195
+ const completionCost = (completionTokens / 1000) * pricingUsed.completion;
196
+ const totalCost = promptCost + completionCost;
197
+
198
+ return {
199
+ model,
200
+ promptTokens,
201
+ completionTokens,
202
+ totalTokens,
203
+ promptCost,
204
+ completionCost,
205
+ totalCost,
206
+ pricingUsed,
207
+ };
208
+ }
209
+
210
+ /**
211
+ * Gets token count using OpenAI's tiktoken library.
212
+ *
213
+ * @since 1.0.0
214
+ *
215
+ * @param {string} text - Text to count tokens for.
216
+ * @param {string} model - Model to use for tokenization.
217
+ *
218
+ * @return {number} Token count.
219
+ */
220
+ getTokenCount(text, model = DEFAULT_MODEL) {
221
+ if (!text || typeof text !== 'string') {
222
+ return 0;
223
+ }
224
+
225
+ const encoding = getEncodingForModel(model);
226
+
227
+ if (!encoding) {
228
+ return Math.ceil(text.length / 4);
229
+ }
230
+
231
+ try {
232
+ return encoding.encode(text).length;
233
+ } catch (error) {
234
+ this.logger.warn(`Failed to get exact token count: ${error.message}`);
235
+
236
+ return Math.ceil(text.length / 4);
237
+ }
238
+ }
239
+
240
+ /**
241
+ * Gets supported OpenAI models.
242
+ * Returns all models from the pricing configuration.
243
+ *
244
+ * @since 1.0.0
245
+ *
246
+ * @return {Array<string>} Supported model identifiers.
247
+ */
248
+ getSupportedModels() {
249
+ if (this.providerPricing && this.providerPricing.models) {
250
+ return Object.keys(this.providerPricing.models).sort();
251
+ }
252
+
253
+ return [...KNOWN_MODELS].sort();
254
+ }
255
+
256
+ /**
257
+ * Gets OpenAI model pricing.
258
+ *
259
+ * @since 1.0.0
260
+ *
261
+ * @param {string} model - Model to get pricing for.
262
+ *
263
+ * @return {Object} Pricing information.
264
+ */
265
+ getModelPricing(model) {
266
+ if (!this.providerPricing) {
267
+ return FALLBACK_PRICING.fallback;
268
+ }
269
+
270
+ return this.providerPricing.models[model] || this.providerPricing.fallback;
271
+ }
272
+
273
+ /**
274
+ * Gets the provider name.
275
+ *
276
+ * @since 1.0.0
277
+ *
278
+ * @return {string} Provider name.
279
+ */
280
+ getProviderName() {
281
+ return 'openai';
282
+ }
283
+
284
+ /**
285
+ * Estimates output tokens based on input tokens.
286
+ * Uses a conservative multiplier for OpenAI models.
287
+ *
288
+ * @since 1.0.0
289
+ *
290
+ * @param {number} inputTokens - Number of input tokens.
291
+ * @param {string} targetLang - Target language (unused in base implementation).
292
+ *
293
+ * @return {number} Estimated output tokens.
294
+ */
295
+ estimateOutputTokens(inputTokens, targetLang) {
296
+ // Use conservative.1.4x multiplier for OpenAI.
297
+ return Math.round(inputTokens * 1.4);
298
+ }
299
+
300
+ /**
301
+ * Gets OpenAI-specific fallback pricing when pricing file cannot be loaded.
302
+ *
303
+ * @since 1.0.0
304
+ *
305
+ * @return {Object} OpenAI fallback pricing structure.
306
+ *
307
+ * @protected
308
+ */
309
+ _getFallbackPricing() {
310
+ return FALLBACK_PRICING;
311
+ }
312
+
313
+ /**
314
+ * Handles dry-run mode by estimating costs without API calls.
315
+ *
316
+ * @since 1.0.0
317
+ *
318
+ * @param {Array} messages - Chat messages for the API.
319
+ * @param {string} model - Model to use.
320
+ * @param {Array} batch - Translation batch.
321
+ * @param {number} pluralCount - Number of plural forms for target language.
322
+ *
323
+ * @return {Object} Dry-run result with estimated costs.
324
+ *
325
+ * @private
326
+ */
327
+ _handleDryRun(messages, model, batch, pluralCount, dictionaryCount) {
328
+ // Calculate input tokens.
329
+ const fullPrompt = messages.map((m) => m.content).join('\n');
330
+ const inputTokens = this.getTokenCount(fullPrompt, model);
331
+
332
+ // Estimate output tokens.
333
+ const userMessageTokens = this.getTokenCount(messages[1].content, model);
334
+ const estimatedOutputTokens = this.estimateOutputTokens(userMessageTokens);
335
+
336
+ // Calculate estimated costs.
337
+ const pricing = this.getModelPricing(model);
338
+ const inputCost = (inputTokens / 1000) * pricing.prompt;
339
+ const outputCost = (estimatedOutputTokens / 1000) * pricing.completion;
340
+ const totalCost = inputCost + outputCost;
341
+
342
+ // Generate dry run translations with proper plural forms.
343
+ const translations = batch.map((item) => {
344
+ const msgstr = Array(pluralCount).fill(`[DRY RUN] ${item.msgid}`);
345
+
346
+ return { msgid: item.msgid, msgstr };
347
+ });
348
+
349
+ return {
350
+ success: true,
351
+ translations,
352
+ usage: {
353
+ prompt_tokens: inputTokens,
354
+ completion_tokens: estimatedOutputTokens,
355
+ total_tokens: inputTokens + estimatedOutputTokens,
356
+ },
357
+ cost: {
358
+ model,
359
+ promptTokens: inputTokens,
360
+ completionTokens: estimatedOutputTokens,
361
+ totalTokens: inputTokens + estimatedOutputTokens,
362
+ promptCost: inputCost,
363
+ completionCost: outputCost,
364
+ totalCost,
365
+ pricingUsed: pricing,
366
+ isDryRun: true,
367
+ dictionaryCount,
368
+ },
369
+ isDryRun: true,
370
+ debugData: {
371
+ messages,
372
+ batchSize: batch.length,
373
+ },
374
+ validationStats: {
375
+ missingPluralForms: 0,
376
+ insufficientForms: 0,
377
+ excessForms: 0,
378
+ incompleteForms: 0,
379
+ },
380
+ };
381
+ }
382
+
383
+ /**
384
+ * Makes API call with retry logic.
385
+ *
386
+ * @since 1.0.0
387
+ *
388
+ * @param {Array} messages - Chat messages.
389
+ * @param {string} model - Model to use.
390
+ * @param {Array} batch - Translation batch.
391
+ * @param {number} maxRetries - Maximum retries.
392
+ * @param {number} retryDelayMs - Retry delay.
393
+ * @param {Function} retryProgressCallback - Optional callback for retry progress updates.
394
+ * @param {Object} debugConfig - Optional debug configuration object.
395
+ * @param {number} pluralCount - Number of plural forms for target language.
396
+ *
397
+ * @return {Promise<Object>} API call result.
398
+ *
399
+ * @private
400
+ */
401
+ async _makeApiCallWithRetries(messages, model, batch, maxRetries, retryDelayMs, retryProgressCallback = null, debugConfig = null, pluralCount = 1, dictionaryCount = 0) {
402
+ let lastError = null;
403
+ let attemptsMade = 0;
404
+ let failedUsage = null;
405
+
406
+ // Debug: Log complete conversation at verbose level.3.
407
+ this.logger.debug('=== FULL CONVERSATION WITH AI ===');
408
+
409
+ messages.forEach((message, index) => {
410
+ this.logger.debug(`Message ${index + 1} (${message.role}):`);
411
+ this.logger.debug(message.content);
412
+ if (index < messages.length - 1) {
413
+ this.logger.debug('---');
414
+ }
415
+ });
416
+
417
+ this.logger.debug('=== END CONVERSATION ===');
418
+
419
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
420
+ try {
421
+ // Notify progress callback about retry status.
422
+ this._notifyRetryProgress(retryProgressCallback, attempt, maxRetries);
423
+
424
+ if (attempt > 0) {
425
+ this.logger.info(`Retry attempt ${attempt}/${maxRetries} after ${retryDelayMs}ms delay`);
426
+
427
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
428
+ }
429
+
430
+ // Handle test mode failure simulation.
431
+ this._handleTestModeFailures(attempt, maxRetries);
432
+
433
+ const response = await this.client.chat.completions.create(buildRequestParams(model, messages, this._calculateMaxTokens(model, batch.length), this.config.temperature ?? 0.1, this.config.reasoningEffort));
434
+
435
+ // Debug: Log raw AI response at verbose level.3.
436
+ this.logger.debug('=== RAW AI RESPONSE ===');
437
+ this.logger.debug(response.choices[0].message.content);
438
+ this.logger.debug('=== END RAW RESPONSE ===');
439
+
440
+ // Save debug files if enabled.
441
+ if (debugConfig && debugConfig.saveDebugInfo) {
442
+ await this._saveDebugFiles(messages, response, debugConfig, batch.length);
443
+ }
444
+
445
+ // A truncated response still yields whatever complete blocks arrived before the
446
+ // cut, so accepting it would write the rest out as blank msgstrs under a success
447
+ // status. Discard the partial batch instead. Reasoning models hit this easily,
448
+ // since their hidden reasoning is charged against the same completion budget.
449
+ if (response.choices[0].finish_reason === 'length') {
450
+ const reasoningTokens = response.usage?.completion_tokens_details?.reasoning_tokens || 0;
451
+ const reasoningNote = reasoningTokens > 0 ? ` (${reasoningTokens} of them spent on reasoning)` : '';
452
+
453
+ const truncationError = new Error(`Response truncated after ${response.usage?.completion_tokens || 0} completion tokens${reasoningNote}. Raise --max-tokens, lower --batch-size, or choose a different model.`);
454
+
455
+ truncationError.code = TRUNCATED_ERROR_CODE;
456
+ truncationError.usage = response.usage;
457
+
458
+ throw truncationError;
459
+ }
460
+
461
+ // Parse response.
462
+ const { translations, validationStats } = this._parseApiResponse(response.choices[0].message.content, batch, pluralCount, dictionaryCount);
463
+
464
+ // Debug: Log parsed translations at verbose level.3.
465
+ this.logger.debug('=== PARSED TRANSLATIONS ===');
466
+
467
+ translations.forEach((translation, index) => {
468
+ this.logger.debug(`${index + 1}. "${translation.msgid}" → ${JSON.stringify(translation.msgstr)}`);
469
+ });
470
+
471
+ this.logger.debug('=== END PARSED TRANSLATIONS ===');
472
+
473
+ const cost = this.calculateCost(response.usage, model);
474
+
475
+ // Notify progress callback that we're no longer retrying.
476
+ this._notifyRetryProgress(retryProgressCallback, attempt, maxRetries, false);
477
+
478
+ return {
479
+ success: true,
480
+ translations,
481
+ usage: response.usage,
482
+ cost,
483
+ isDryRun: false,
484
+ debugData: {
485
+ messages,
486
+ response: response.choices[0].message.content,
487
+ },
488
+ dictionaryCount,
489
+ validationStats,
490
+ };
491
+ } catch (error) {
492
+ lastError = error;
493
+ attemptsMade = attempt + 1;
494
+
495
+ if (error.usage) {
496
+ failedUsage = error.usage;
497
+ }
498
+
499
+ this.logger.warn(`API call attempt ${attempt + 1} failed: ${error.message}`);
500
+
501
+ // Don't retry on certain errors.
502
+ if (this._shouldStopRetrying(error)) {
503
+ break;
504
+ }
505
+ }
506
+ }
507
+
508
+ // Final progress callback update to clear retry status.
509
+ this._notifyRetryProgress(retryProgressCallback, maxRetries, maxRetries, false);
510
+
511
+ return {
512
+ success: false,
513
+ error: `Failed after ${attemptsMade} attempt${attemptsMade === 1 ? '' : 's'}. Last error: ${lastError.message}`,
514
+ translations: [],
515
+ cost: failedUsage ? this.calculateCost(failedUsage, model) : { totalCost: 0 },
516
+ dictionaryCount,
517
+ };
518
+ }
519
+
520
+ /**
521
+ * Notifies retry progress callback if provided.
522
+ *
523
+ * @private
524
+ * @since 1.0.0
525
+ * @param {Function} callback - Progress callback function.
526
+ * @param {number} attempt - Current attempt number.
527
+ * @param {number} maxRetries - Maximum retry attempts.
528
+ * @param {boolean} isRetrying - Whether currently retrying.
529
+ */
530
+ _notifyRetryProgress(callback, attempt, maxRetries, isRetrying = true) {
531
+ if (!callback) {
532
+ return;
533
+ }
534
+
535
+ callback({
536
+ isRetrying: isRetrying && attempt > 0,
537
+ attempt,
538
+ maxRetries,
539
+ });
540
+ }
541
+
542
+ /**
543
+ * Determines if retrying should stop based on error type.
544
+ *
545
+ * @private
546
+ * @since 1.0.0
547
+ * @param {Error} error - The error that occurred.
548
+ * @return {boolean} True if retrying should stop.
549
+ */
550
+ _shouldStopRetrying(error) {
551
+ // Truncation is deterministic: an identical retry costs money and fails the same way.
552
+ return error.status === 401 || error.status === 403 || error.code === TRUNCATED_ERROR_CODE;
553
+ }
554
+
555
+ /**
556
+ * Handles test mode failure simulation for retry logic testing.
557
+ *
558
+ * @private
559
+ * @since 1.0.0
560
+ * @param {number} attempt - Current attempt number.
561
+ * @param {number} maxRetries - Maximum retry attempts.
562
+ * @throws {Error} Simulated API error for testing.
563
+ */
564
+ _handleTestModeFailures(attempt, maxRetries) {
565
+ if (!this.config.testRetryFailureRate || this.config.testRetryFailureRate <= 0) {
566
+ return;
567
+ }
568
+
569
+ const shouldFail = Math.random() < this.config.testRetryFailureRate;
570
+
571
+ if (!shouldFail) {
572
+ return;
573
+ }
574
+
575
+ // Check if we should fail this attempt.
576
+ const isFinalAttempt = attempt === maxRetries;
577
+ const shouldProtectFinalAttempt = !this.config.testAllowCompleteFailure;
578
+
579
+ if (isFinalAttempt && shouldProtectFinalAttempt) {
580
+ this.logger.info(`🧪 TEST MODE: Would simulate failure but allowing final attempt to succeed (final attempt protection enabled)`);
581
+ return;
582
+ }
583
+
584
+ this.logger.warn(`🧪 TEST MODE: Simulating API failure (attempt ${attempt + 1}/${maxRetries + 1}) - failure rate: ${(this.config.testRetryFailureRate * 100).toFixed(1)}%`);
585
+
586
+ const errorType = this._getRandomTestError();
587
+
588
+ this.logger.warn(`🧪 TEST MODE: Simulating ${errorType.status ? `HTTP ${errorType.status}` : 'network'} error: ${errorType.message}`);
589
+
590
+ const testError = new Error(errorType.message);
591
+
592
+ if (errorType.status) {
593
+ testError.status = errorType.status;
594
+ }
595
+
596
+ // For rate limiting, add some extra properties that OpenAI API might include.
597
+ if (errorType.status === 429) {
598
+ testError.response = {
599
+ headers: {
600
+ 'retry-after': '60',
601
+ 'x-ratelimit-remaining': '0',
602
+ },
603
+ };
604
+ }
605
+
606
+ throw testError;
607
+ }
608
+
609
+ /**
610
+ * Gets a random test error for failure simulation.
611
+ *
612
+ * @private
613
+ *
614
+ * @since 1.0.0
615
+ *
616
+ * @return {Object} Random error configuration.
617
+ */
618
+ _getRandomTestError() {
619
+ const errorTypes = [
620
+ { status: 429, message: 'Rate limit exceeded. Please retry after 60 seconds.' },
621
+ { status: 500, message: 'Internal server error' },
622
+ { status: 502, message: 'Bad gateway' },
623
+ { status: 503, message: 'Service temporarily unavailable' },
624
+ { status: 504, message: 'Gateway timeout' },
625
+ { status: null, message: 'Network connection failed' }, // Simulate network error.
626
+ ];
627
+
628
+ return errorTypes[Math.floor(Math.random() * errorTypes.length)];
629
+ }
630
+
631
+ /**
632
+ * Parses API response and extracts translations.
633
+ *
634
+ * @since 1.0.0
635
+ *
636
+ * @param {string} responseContent - API response content.
637
+ * @param {Array} batch - Original batch for fallback.
638
+ * @param {number} pluralCount - Number of plural forms for target language.
639
+ * @param {number} dictionaryCount - Number of dictionary entries to skip.
640
+ *
641
+ * @return {Object} Object with translations array and validationStats.
642
+ *
643
+ * @private
644
+ */
645
+ _parseApiResponse(responseContent, batch, pluralCount, dictionaryCount = 0) {
646
+ try {
647
+ const verbosityLevel = this.config.verboseLevel || 1;
648
+ const { translations, validationStats } = parseXmlResponse(responseContent, batch, pluralCount, this.logger, dictionaryCount, verbosityLevel);
649
+
650
+ return { translations, validationStats };
651
+ } catch (error) {
652
+ if ((this.config.verboseLevel || 1) >= 2) {
653
+ this.logger.warn(`Failed to parse API response: ${error.message}`);
654
+ }
655
+
656
+ // Return empty translations as fallback.
657
+ return {
658
+ translations: batch.map((item) => ({
659
+ msgid: item.msgid,
660
+ msgstr: Array(pluralCount).fill(''),
661
+ })),
662
+ validationStats: {
663
+ missingPluralForms: 0,
664
+ insufficientForms: 0,
665
+ excessForms: 0,
666
+ incompleteForms: 0,
667
+ },
668
+ };
669
+ }
670
+ }
671
+
672
+ /**
673
+ * Saves API request and response data to debug files when debug mode is enabled.
674
+ * Creates timestamped files with detailed information for troubleshooting.
675
+ *
676
+ * @private
677
+ *
678
+ * @since 1.0.0
679
+ *
680
+ * @param {Array} messages - The API request messages sent to OpenAI.
681
+ * @param {Object} response - The full API response from OpenAI.
682
+ * @param {Object} debugConfig - Debug configuration object.
683
+ * @param {number} batchSize - Size of the batch for max_tokens calculation.
684
+ *
685
+ * @return {Promise<void>} Resolves when debug files are saved successfully.
686
+ */
687
+ async _saveDebugFiles(messages, response, debugConfig, batchSize) {
688
+ try {
689
+ const fs = await import('fs');
690
+ const path = await import('path');
691
+
692
+ // Create debug directory if it doesn't exist.
693
+ const debugDir = path.join(debugConfig.outputDir || '.', 'debug');
694
+
695
+ if (!fs.existsSync(debugDir)) {
696
+ fs.mkdirSync(debugDir, { recursive: true });
697
+ }
698
+
699
+ // Create timestamp for unique file naming.
700
+ const now = new Date();
701
+ const dateStr = now.toISOString().slice(0, 10).replace(/-/g, ''); // YYYYMMDD.
702
+ const timeStr = now.toISOString().slice(11, 16).replace(':', ''); // HHMM.
703
+ const batchStr = `${debugConfig.batchNum}-of-${debugConfig.totalBatches}`;
704
+ const filePrefix = `${dateStr}--${timeStr}--${debugConfig.targetLang}--${batchStr}`;
705
+
706
+ // Prepare debug data with metadata and complete request parameters.
707
+ const { totalBatches } = debugConfig;
708
+ const { model } = response;
709
+ const debugData = {
710
+ metadata: {
711
+ timestamp: new Date().toISOString(),
712
+ targetLanguage: debugConfig.targetLang,
713
+ batchNumber: debugConfig.batchNum,
714
+ totalBatches,
715
+ model,
716
+ },
717
+ request: {
718
+ ...buildRequestParams(model, messages, this._calculateMaxTokens(model, batchSize), this.config.temperature ?? 0.1, this.config.reasoningEffort),
719
+ systemPromptLength: messages[0].content.length,
720
+ userMessageLength: messages[1].content.length,
721
+ },
722
+ response: {
723
+ id: response.id,
724
+ object: response.object,
725
+ created: response.created,
726
+ model: response.model,
727
+ choices: response.choices,
728
+ usage: response.usage,
729
+ systemFingerprint: response.system_fingerprint,
730
+ },
731
+ };
732
+
733
+ // Save debug file.
734
+ const debugFilePath = path.join(debugDir, `${filePrefix}.json`);
735
+
736
+ fs.writeFileSync(debugFilePath, JSON.stringify(debugData, null, 2), 'utf8');
737
+
738
+ this.logger.debug(`Debug file saved: ${debugFilePath}`);
739
+ } catch (error) {
740
+ this.logger.warn(`Failed to save debug files: ${error.message}`);
741
+ }
742
+ }
743
+
744
+ /**
745
+ * Calculates max_tokens value with smart auto-calculation.
746
+ * When not configured, estimates based on batch size and expected output.
747
+ *
748
+ * @private
749
+ * @since 1.0.0
750
+ * @param {string} model - OpenAI model (for token estimation).
751
+ * @param {number} batchSize - Number of items in the batch.
752
+ * @return {number} Max tokens value.
753
+ */
754
+ _calculateMaxTokens(model, batchSize) {
755
+ // Use configured value if provided.
756
+ if (this.config.maxTokens) {
757
+ this.logger.debug(`Using configured max_tokens: ${this.config.maxTokens} for batch of ${batchSize} string${batchSize === 1 ? '' : 's'}`);
758
+
759
+ return this.config.maxTokens;
760
+ }
761
+
762
+ // Auto-calculate based on batch size and expected output.
763
+ const estimatedTokensPerString = this._estimateTokensPerString();
764
+ const estimatedOutputTokens = batchSize * estimatedTokensPerString;
765
+
766
+ // Add safety buffer (30%) to account for:
767
+ // - Longer translations in some languages.
768
+ // - XML formatting overhead.
769
+ // - Some strings being longer than average.
770
+ const safetyBuffer = 1.3;
771
+ const calculatedMaxTokens = Math.round(estimatedOutputTokens * safetyBuffer);
772
+
773
+ // Models on the `max_completion_tokens` path spend hidden reasoning tokens out of this
774
+ // same budget before emitting any text, and that cost is largely fixed rather than
775
+ // proportional to the batch. Sizing from visible output alone starves small batches.
776
+ // Raising the ceiling is free: billing follows the tokens actually generated.
777
+ const reasoningHeadroom = reasoningHeadroomTokens(model, this.config.reasoningEffort);
778
+
779
+ // Apply reasonable bounds.
780
+ const minTokens = 100; // Minimum for any response.
781
+ const maxTokens = 32768; // Potomatic cost/safety ceiling; keep aligned with config validation.
782
+ const finalMaxTokens = Math.max(minTokens, Math.min(maxTokens, calculatedMaxTokens + reasoningHeadroom));
783
+
784
+ this.logger.debug(`Auto-calculated max_tokens: ${finalMaxTokens} for batch of ${batchSize} string${batchSize === 1 ? '' : 's'} (estimated: ${estimatedOutputTokens}, with 30% buffer: ${calculatedMaxTokens}, reasoning headroom: ${reasoningHeadroom})`);
785
+
786
+ return finalMaxTokens;
787
+ }
788
+
789
+ /**
790
+ * Estimates average tokens needed per string translation.
791
+ * Based on typical translation patterns and XML formatting overhead.
792
+ *
793
+ * @private
794
+ * @since 1.0.0
795
+ * @return {number} Estimated tokens per translated string.
796
+ */
797
+ _estimateTokensPerString() {
798
+ // Conservative estimate based on.:
799
+ // - Average translation length (50-80 tokens.)
800
+ // - XML formatting overhead (<translation id="1".>...</translation>)
801
+ // - Plural forms (may double the output.)
802
+ // - Some strings being longer than average.
803
+ return 120;
804
+ }
805
+ }