AI - markhowellsmead/helpers GitHub Wiki

REST API endpoint to translate text

/**
 * Call OpenAI API to translate text. Minimal implementation using cURL.
 * Replace or extend with official SDK as needed.
 *
 * @param string $apiKey
 * @param string $text
 * @param string $lang
 * @return string
 */
private function callOpenAiTranslate(string $apiKey, string $text, string $lang): string
{
	switch ($lang) {
		case 'de':
			$system = 'You are a helpful translator. Translate the given text to polite and professional German as it is used in Switzerland. Use the appropriate grammar, spelling and punctuation for Schriftdeutsch in Switzerland -- do not use ß and use « and » as quotes.';
			break;
		case 'en':
			$system = 'You are a helpful translator. Translate the given text to polite and professional British English. Use British English grammar, spelling and punctuation.';
			break;
		default:
			throw new WP_Error('Unsupported language: ' . $lang);
	}

	$payload = json_encode([
		'model' => 'gpt-3.5-turbo',
		'messages' => [
			['role' => 'system', 'content' => $system],
			['role' => 'user', 'content' => $text],
		],
		'max_tokens' => 2000,
	]);

	$ch = curl_init('https://api.openai.com/v1/chat/completions');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER, [
		'Content-Type: application/json',
		'Authorization: Bearer ' . $apiKey,
	]);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);

	$response = curl_exec($ch);
	if ($response === false) {
		$err = curl_error($ch);
		curl_close($ch);
		throw new \RuntimeException('cURL error: ' . $err);
	}

	$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);

	$data = json_decode($response, true);
	if ($code >= 400 || empty($data['choices'][0]['message']['content'])) {
		throw new \RuntimeException('OpenAI error: ' . ($data['error']['message'] ?? 'unknown'));
	}

	return trim((string) $data['choices'][0]['message']['content']);
}