With this example you can translate product or post data to any language you want. Also response will be a valid JSON formatted. You can check the first promp in “content” value in “messages” which means promps for this example we order to have responses in json format and we want to keep keys the same so you can use them later.
Also make sure you changed “chatgpt_api_key” with yours in the function.
Also you can change mobel by editing “gpt-4o” to whatever you want.
PHP
<?php
/**
* Translate product data via chatgpt api
*
* @param array $product_data
*
* @return array
*
*/
function translate_product_data( array $product_data , $tanguage_to ) : array
{
file_put_contents( __DIR__ . '/translate_product_data_request.json', json_encode( $product_data, JSON_PRETTY_PRINT ) );
$chatgpt_api_key = "OPENAI_API_KEY"
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "https://api.openai.com/v1/chat/completions" );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( [
"model" => "gpt-4o",
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant. You will translate product and product name, description etc. data to $tanguage_to. You will get input data as json and you will return data in the same json format and keys. Response shoul not have anything like '```json'. only should have json data to decode."
],
[ "role" => "user", "content" => json_encode( $product_data ) ]
],
"temperature" => 1,
"max_tokens" => 4000,
"top_p" => 1,
"frequency_penalty" => 0,
"presence_penalty" => 0
] ) );
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
"Authorization: Bearer $chatgpt_api_key",
] );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec( $ch );
curl_close( $ch );
$response = json_decode( $response, true );
file_put_contents( __DIR__ . '/translate_response.json', json_encode( $response, JSON_PRETTY_PRINT ) );
if ( isset( $response['error'] ) ) {
exit( $response['error']['message'] );
}
return json_decode( $response['choices'][0]['message']['content'], true );
}
You should also check the returned array that if it has the keys you send to make sure there is no problem.