Open AI error response in PHP

Hello - I’ve been testing the process of making openAI API calls in PHP (file_get_contents) using the code below. It’s failing at: file_get_contents($url, false, $context). If I remove the ‘model’ parameter, it returns a ‘non-sense’ completion that is remotely related to the prompt, at times even using ‘dirty words’. The JSON seems to be well formed and I have a valid API key…any thoughts would be greatly appreciated!

$sPrompt = “what is the capital of pennsylvania”;

$data = [
‘prompt’ => $sPrompt,
‘max_tokens’ => 256,
‘frequency_penalty’ => 0,
‘model’ => ‘gpt-3.5-turbo’
];

$jsonData = json_encode($data);

// Check if the JSON encoding was successful
if ($jsonData === false) {
// Handle JSON encoding error
} else {
$apiKey = ‘** API_KEY - my actual key is here **’;

$url = 'https://api.openai.com/v1/engines/davinci-codex/completions';
//$url = 'https://api.openai.com/v1/engines/davinci/completions';
$headers = [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey,
];
$options = [
    'http' => [
        'header' => implode("\r\n", $headers),
        'method' => 'POST',
        'content' => $jsonData,
    ],
];

//echo $jsonData;

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response === false) {
    // Handle API request error
    echo 'Error: Unable to connect to the OpenAI API';
} else {
    // Process the API response
    $decodedResponse = json_decode($response, true);
    // Access the returned data
    // ...
    echo $decodedResponse['choices'][0]['text']; 
}
1 Like

Welcome to our dev community!

I believe your problem is that you’re not formatting the “prompt” correctly for gpt-35 which is a chat completion model…

Here’s what it looks like in Python. Basically, you want to send an object…

  messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who won the world series in 2020?"},
        {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
        {"role": "user", "content": "Where was it played?"}
    ]

You can check here…

… for more on endpoint compatability.

1 Like

PaulBellow - thanks for the response.
I tried reformatting as per the article, but it’s still failing - still searching for a solution.

$data = [
‘model’ => ‘gpt-3.5-turbo’,
‘messages’ => [“role” => “user”, “content” => $sPrompt],
‘max_tokens’ => 256,
‘frequency_penalty’ => 0
];

You need more than just user role, I believe.

What error message are you getting?

If you’re trying to use GPT your URL is wrong. Here’s working PHP code using curl

$data = [
        'model'    => 'gpt-3.5-turbo',
        'messages' => [
                ['role' => 'user', 'content' => $prompt],
        ]
];

$headers = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $openaiApiKey,
        'OpenAI-Organization: ' . $openaiOrg,
];

$options = [
        CURLOPT_URL            => 'https://api.openai.com/v1/chat/completions',
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER         => false,
        CURLOPT_HTTPHEADER     => $headers,
];
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
curl_close($ch);

$response = json_decode($response);
echo $response->choices[0]->message->content;
3 Likes

Missed that with the malformed example code from OP. Thanks!

Thank you novaPhil and PaulBellow. It worked.

I was using the wrong URL and I needed fix the decoded JSON - and add another set of square brackets to the messages array: ‘messages’ => [[“role” => “user”, “content” => $sPrompt]],
You guys rock!

1 Like