phpopenai-apichatgpt-api

OpenAI Chat Completions API error in WordPress PHP code: "Invalid URL (POST /v4/engines/davinci-codex/completions)"


I've asked ChatGPT to generate a code to be incorporated in WordPress function.php to generate tags automatically for all my newly created or updated posts.

Here is the code:

function add_tags_with_gpt($post_ID) {
    // Vérifier si le contenu de l'article a réellement changé
    $post = get_post($post_ID);
    $old_content = get_post_meta($post_ID, '_old_content', true);
    $new_content = $post->post_content;
    if ($old_content === $new_content) {
        return; // Le contenu n'a pas changé, donc on ne fait rien
    }
    update_post_meta($post_ID, '_old_content', $new_content);

    // Utiliser l'API OpenAI pour générer des tags
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v4/engines/davinci-codex/completions');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
        'prompt' => 'Generate tags for a blog post with the following content: '.$new_content,
        'max_tokens' => 60
    )));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer your_openai_api_key', // Remplacez 'your_openai_api_key' par votre véritable clé API
        'Content-Type: application/json'
    ));
    $response = curl_exec($ch);
    if (!$response) {
        // Enregistrer l'erreur dans le fichier de log de débogage de WordPress
        error_log('Erreur lors de la génération de tags: ' . curl_error($ch));
        return;
    }
    curl_close($ch);

    // Enregistrer la réponse de l'API dans le fichier de log de débogage de WordPress
    error_log('Réponse de l\'API OpenAI : ' . $response);

    $response_data = json_decode($response, true);
    if(!isset($response_data['choices'][0]['text'])) {
        error_log('Erreur: La réponse de l\'API ne contient pas de tags');
        return;
    }
    $tags = explode(',', $response_data['choices'][0]['text']);
    $tags = array_slice($tags, 0, 8);

    // Valider et nettoyer les tags
    $tags = array_map('sanitize_text_field', $tags);
    $tags = array_map('wp_strip_all_tags', $tags);
    $tags = array_filter($tags, function($tag) {
        return strlen($tag) > 2 && strlen($tag) <= 20; // Exclure les tags de moins de 3 caractères et de plus de 20 caractères
    });

    // Ajouter les tags à l'article
    wp_set_post_tags($post_ID, $tags, true);
}
add_action('save_post', 'add_tags_with_gpt');

The problem is that the code doesn't work and returns this error message in debug.log:

[23-Jul-2023 15:16:27 UTC] Réponse de l'API OpenAI : {
  "error": {
    "message": "Invalid URL (POST /v4/engines/davinci-codex/completions)",
    "type": "invalid_request_error",
    "param": null,
    "code": null
  }
}

[23-Jul-2023 15:16:27 UTC] Erreur: La réponse de l'API ne contient pas de tags
[23-Jul-2023 15:16:34 UTC] PHP Deprecated:  str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated in /home/***/webapps/***/wp-includes/formatting.php on line 4303

Any idea what the issue is and how to fix it? The problem doesn't come from the API key that I pass from my OpenAI account into the code.

Many thanks!


Solution

  • All Engines API endpoints are deprecated.

    Screenshot

    Use the Chat Completions API endpoint.

    Change the URL from this...

    https://api.openai.com/v4/engines/davinci-codex/completions
    

    ...to this.

    https://api.openai.com/v1/chat/completions
    

    There are 4 required parameters for the Chat Completions API:

    See my past answer for a working example in PHP using the gpt-3.5-turbo model.