lang_translation_run()
Description
Translate with a bounded queue. Write validated entries as each request completes.Parameters
| Column | Type | Default | Description |
|---|---|---|---|
| $api_key | string | OpenAI API key. | |
| $models | list |
Models in retry order. | |
| $groups | array | Source batches keyed by component. | |
| $context | array | Component prompt contexts and shared usage index. | |
| $accept | callable | Receives the component, accepted set and model ID. | |
| $parallel | int | Maximum concurrent requests. |
Return
| array | Untranslated keys and failure reasons grouped by component and locale. |
Location
include/lang_translation_functions.php lines 509 to 755
Definition
function lang_translation_run(
string $api_key,
array $models,
array $groups,
array $context,
callable $accept,
int $parallel = 16
): array {
$queue = new SplQueue();
$total = 0;
foreach ($groups as $component => $batches) {
foreach ($batches as $batch) {
$queue->enqueue([
'component' => $component, 'batch' => $batch, 'model' => 0, 'retries' => 0, 'ready' => 0.0,
]);
$total += lang_translation_batch_size($batch);
}
}
$multi = curl_multi_init();
$active = [];
$free_slots = array_fill(1, $parallel, true);
$slots = array_fill(1, $parallel, ['state' => 'Idle', 'detail' => '', 'style' => 'muted']);
$rendered_rows = 0;
$failed = [];
$failed_count = 0;
$translated = 0;
$frame = 0;
$pause_until = 0.0;
$interactive = cli_is_interactive();
$terminal_size = cli_terminal_size();
$progress_interval = $interactive ? 0.125 : 5;
$next_progress = 0.0;
try {
while (!$queue->isEmpty() || $active !== []) {
$now = microtime(true);
for (
$pending = $queue->count();
$pending > 0 && count($active) < $parallel && $now >= $pause_until;
--$pending
) {
$job = $queue->dequeue();
if ($job['ready'] > $now) {
$queue->enqueue($job);
continue;
}
$model = $models[$job['model']];
$component_context = $context['components'][$job['component']];
$body = lang_translation_request(
$model,
$job['batch'],
$component_context + ['usage' => $context['usage']]
);
$request = lang_translation_handle($api_key, $body);
$handle = $request['handle'];
if (curl_multi_add_handle($multi, $handle) !== CURLM_OK) {
throw new RuntimeException('Could not queue a translation request');
}
$slot = min(array_keys($free_slots));
unset($free_slots[$slot]);
$job['slot'] = $slot;
$locales = array_keys($job['batch']);
$locale_list = implode(', ', array_slice($locales, 0, 4));
if (count($locales) > 4) {
$locale_list .= ' +' . (count($locales) - 4);
}
$size = lang_translation_batch_size($job['batch']);
$slots[$slot] = [
'state' => $job['model'] > 0 || $job['retries'] > 0 ? 'Retrying' : 'Translating',
'detail' => "{$component_context['component']} · {$size} strings · {$locale_list} · {$model}",
'style' => 'heading',
'started' => microtime(true),
];
$active[spl_object_id($handle)] = array_replace($job, $request);
}
if ($now >= $next_progress) {
$requests = count($active);
$queued = $queue->count();
$finished = $translated + $failed_count;
if ($interactive) {
$lines = lang_translation_dashboard_lines(
$slots,
$finished,
$total,
$requests,
$queued,
$frame++,
microtime(true)
);
cli_render_status_block($lines, $rendered_rows, $terminal_size);
} else {
cli_progress($finished, $total, "{$requests} active · {$queued} queued");
}
$next_progress = microtime(true) + $progress_interval;
}
if ($active === []) {
usleep(100000);
continue;
}
do {
$status = curl_multi_exec($multi, $running);
} while ($status === CURLM_CALL_MULTI_PERFORM);
if ($status !== CURLM_OK) {
throw new RuntimeException('Could not execute the translation queue');
}
$completed = false;
while ($event = curl_multi_info_read($multi)) {
cli_clear_status_block($rendered_rows);
$completed = true;
$handle = $event['handle'];
$id = spl_object_id($handle);
$job = $active[$id];
$component = $job['component'];
$slot = $job['slot'];
$free_slots[$slot] = true;
$batch = $job['batch'];
$batch_size = lang_translation_batch_size($batch);
$status = curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
$body = json_decode((string) curl_multi_getcontent($handle), true);
curl_multi_remove_handle($multi, $handle);
unset($active[$id]);
unset($job['handle']);
if ($interactive) {
$next_progress = 0.0;
}
$error_code = $body['error']['code'] ?? null;
if ($status === 401 || $status === 403 || $error_code === 'insufficient_quota') {
throw new RuntimeException('OpenAI denied translation requests (HTTP ' . $status . ')');
}
$transient = $event['result'] !== CURLE_OK || $status === 408 || $status === 429 || $status >= 500;
if ($transient && $job['retries'] < 3) {
// Give the service time to recover without repeating successful translations.
$delay = max(2 ** $job['retries'], $job['retry_after']->seconds) + random_int(50, 750) / 1000;
$job['ready'] = microtime(true) + $delay;
++$job['retries'];
if ($status === 429) {
$pause_until = max($pause_until, $job['ready']);
}
$slots[$slot] = [
'state' => 'Backoff',
'detail' => "Retry queued in " . ceil($delay) . 's',
'style' => 'warning',
];
cli_log(' ' . $models[$job['model']] . ": retrying {$batch_size} strings in "
. ceil($delay) . ' seconds after a temporary failure.', 'warning');
$queue->enqueue($job);
continue;
}
$choice = $body['choices'][0] ?? [];
if (($choice['finish_reason'] ?? '') === 'length' && $batch_size > 1) {
$slots[$slot] = [
'state' => 'Split',
'detail' => "{$batch_size} strings queued in smaller requests",
'style' => 'warning',
];
cli_log(" Splitting an incomplete response for {$batch_size} strings.", 'warning');
foreach (lang_translation_batches($batch, (int) ceil($batch_size / 2)) as $smaller_batch) {
$queue->enqueue([
'component' => $component,
'batch' => $smaller_batch,
'model' => $job['model'],
'retries' => 0,
'ready' => 0.0,
]);
}
continue;
}
$message = $choice['message'] ?? [];
$success = $status >= 200 && $status < 300 && ($choice['finish_reason'] ?? '') === 'stop'
&& empty($message['refusal']) && is_string($message['content'] ?? null);
if ($success) {
$results = lang_translation_batch_results($batch, json_decode($message['content'], true));
} else {
$reason = $status >= 400 ? 'HTTP ' . $status : 'missing, refused or incomplete response';
$results = ['accepted' => [], 'rejected' => array_map(
static fn(array $entries): array => array_fill_keys(array_keys($entries), $reason),
$batch
)];
}
if ($results['accepted'] !== []) {
$accept($component, $results['accepted'], $models[$job['model']]);
}
$saved_count = lang_translation_batch_size($results['accepted']);
$translated += $saved_count;
$retry_count = lang_translation_batch_size($results['rejected']);
$slots[$slot] = [
'state' => $retry_count === 0 ? 'Done' : 'Retry queued',
'detail' => $retry_count === 0
? "{$saved_count} saved"
: "{$saved_count} saved · {$retry_count} retry",
'style' => $retry_count === 0 ? 'success' : 'warning',
];
if ($results['rejected'] !== []) {
$next = $job['model'] + 1;
if (isset($models[$next])) {
$noun = $retry_count === 1 ? 'string' : 'strings';
$previous_model = $models[$job['model']];
cli_log(
" Retrying {$retry_count} {$noun} with {$models[$next]} after {$previous_model}.",
'warning'
);
$component_name = $context['components'][$component]['component'];
$retry = [];
foreach ($results['rejected'] as $locale => $entries) {
$retry[$locale] = array_intersect_key($batch[$locale], $entries);
foreach ($entries as $key => $reason) {
$source = $retry[$locale][$key];
$text = is_string($source) ? $source : json_encode($source, JSON_UNESCAPED_UNICODE);
$preview = rtrim(cli_preview_column((string) $text));
cli_log(" {$component_name}/{$locale} {$key}: {$preview} ({$reason})");
}
}
$queue->enqueue([
'component' => $component,
'batch' => $retry,
'model' => $next, 'retries' => 0, 'ready' => 0.0,
]);
} else {
$failed_count += $retry_count;
$slots[$slot] = [
'state' => 'Failed',
'detail' => "{$retry_count} untranslated · {$saved_count} saved",
'style' => 'error',
];
foreach ($results['rejected'] as $locale => $entries) {
$failed[$component][$locale] = ($failed[$component][$locale] ?? []) + $entries;
}
}
}
}
if (!$completed && $running > 0 && curl_multi_select($multi, min(0.25, $progress_interval)) === -1) {
usleep(10000);
}
}
} finally {
foreach ($active as $job) {
curl_multi_remove_handle($multi, $job['handle']);
}
cli_clear_status_block($rendered_rows);
}
return $failed;
}
This article was last updated 27th November 2026 18:35 Europe/London time based on the source file dated 27th November 2026 17:15 Europe/London time.