Error message Error: Unexpected response structure

I am using php script with api

<?php // Your OpenAI API key $apiKey = 'sk-PAZZ57DQf***********tx'; // The API URL for GPT-3 (or change the model as needed) $apiUrl = 'https://api.openai.com/v1/chat/completions'; $prompt="Geef een voorbeeld van vogels"; // Data payload for the API request $data = [ 'model' => 'gpt-3.5-turbo', 'messages' => [ ['role' => 'user', 'content' => $prompt], ] ]; // Initialize cURL session $curl = curl_init(); // Set cURL options curl_setopt($curl, CURLOPT_URL, $apiUrl); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $apiKey ]); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Execute the API request $response = curl_exec($curl); // Close cURL session curl_close($curl); // Check if the request was successful if ($response) { $decodedResponse = json_decode($response, true); if (isset($decodedResponse['choices'][0]['text'])) { echo "Response from OpenAI: " . trim($decodedResponse['choices'][0]['text']); } else { echo "Error: Unexpected response structure"; } } else { echo "Error: Unable to retrieve response from OpenAI"; } ?>

Unexpected response structure

please advice
Ed Kool

This looks like the kind of mistake an AI with old information would make - using the completions method to get “text” instead of the proper response out of the new chat completions response object.

It also can be fixed (and shown better) by a more trained AI:


Given the structure of the JSON response from the API, where the content you want to access is nested within choices -> message -> content, you will need to modify the response handling part of the PHP code to correctly extract the “content” instead of looking for a “text” field that doesn’t exist. Here’s how you can adjust your PHP script to handle this updated response format:

Updated PHP Code

<?php
// Your OpenAI API key
$apiKey = 'sk-PAZZ57DQf***********tx';

// The API URL for GPT-3 (or change the model as needed)
$apiUrl = 'https://api.openai.com/v1/chat/completions';

$prompt = "Geef een voorbeeld van vogels";

// Data payload for the API request
$data = [
    'model' => 'gpt-3.5-turbo',
    'messages' => [
        ['role' => 'user', 'content' => $prompt],
    ]
];

// Initialize cURL session
$curl = curl_init();

// Set cURL options
curl_setopt($curl, CURLOPT_URL, $apiUrl);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey
]);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

// Execute the API request
$response = curl_exec($curl);

// Close cURL session
curl_close($curl);

// Check if the request was successful
if ($response) {
    $decodedResponse = json_decode($response, true);
    if (isset($decodedResponse['choices'][0]['message']['content'])) {
        echo "Response from OpenAI: " . trim($decodedResponse['choices'][0]['message']['content']);
    } else {
        echo "Error: Unexpected response structure";
    }
} else {
    echo "Error: Unable to retrieve response from OpenAI";
}
?>

Key Changes Made

  1. Accessing the Correct Data:

    • Changed from accessing $decodedResponse['choices'][0]['text'] to $decodedResponse['choices'][0]['message']['content'] based on your JSON structure. This path follows the nesting of your JSON response to correctly extract the assistant’s message content.
  2. Error Handling:

    • The error message for “Unexpected response structure” now more accurately reflects issues related to the existence of the necessary nested data (i.e., checks if the ‘content’ is present where expected).

By updating these parts of your PHP code, the script will correctly handle the response from the API and extract the intended message from the structured JSON. This should resolve issues you might have been facing with incorrect keys and ensure the output displays as expected.