1

I'm writing a simple PHP script with no dependencies to access the ChatGPT API, but it's throwing an error I don't understand:

Here's the script so far:

    $apiKey = "Your-API-Key";
    $url = 'https://api.openai.com/v1/chat/completions';  
    
    $headers = array(
        "Authorization: Bearer {$apiKey}",
        "OpenAI-Organization: YOUR-ORG-STRING", 
        "Content-Type: application/json"
    );
    
    // Define messages
    $messages = array();
    $messages["role"] = "user";
    $messages["content"] = "Hello future overlord!";
    
    // Define data
    $data = array();
    $data["model"] = "gpt-3.5-turbo";
    $data["messages"] = $messages;
    $data["max_tokens"] = 50;

    // init curl
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    
    $result = curl_exec($curl);
    if (curl_errno($curl)) {
        echo 'Error:' . curl_error($curl);
    } else {
        echo $result;
    }
    
    curl_close($curl);

This returns an error from the API:

{"model":"gpt-3.5-turbo","messages":{"role":"user","content":"Hello future overlord!"},"max_tokens":50}{ "error": { "message": "{'role': 'user', 'content': 'Hello future overlord!'} is not of type 'array' - 'messages'", "type": "invalid_request_error", "param": null, "code": null } }

AFAIK, I'm sending the messages param as an array. Where is this going wrong? Is this an issue with json_encode? Why doesn't the API think this is an array?

Thanks in advance!

picsoung
  • 6,314
  • 1
  • 18
  • 35
Bangkokian
  • 6,548
  • 3
  • 19
  • 26
  • 2
    ChatGPT knows the whole documentation of the API, you can simply copy and paste the question you wrote to chat gpt and it will fix and explain the error. Copy pasting answer from chatgpt is not allowed, so I am not doing it. – Obaydur Rahman Mar 19 '23 at 07:35
  • 2
    `json_encode()` will encode a PHP associative array as a JSON object. If you need to create a JSON array you must create a PHP array with numeric indices. I'm not familiar with the API so I can't tell you what you need to do. – Tangentially Perpendicular Mar 19 '23 at 07:37
  • @TangentiallyPerpendicular Yes, but the API requires a JSON string. That's all it accepts. – Bangkokian Mar 19 '23 at 07:39
  • Can you change `$data["messages"] = $messages;` line to ```$data["messages[]"] = $messages;``` and try it again? – Ismail Mar 19 '23 at 07:42
  • There is a PHP library available supported by Laravel community for the same purpose. You might want to have a look. It's got a lot of attention. https://github.com/openai-php/client – Ismail Mar 19 '23 at 07:48
  • @Bangkokian I'm not disputing that. You asked if there is an issue with `json_encode()`. I've explained what that issue is, but I can't tell you how to work around it because I'm not familiar with the API. – Tangentially Perpendicular Mar 19 '23 at 08:00
  • 2
    Does this answer your question? [OpenAI ChatGPT (gpt-3.5-turbo) API: How to access the message content?](https://stackoverflow.com/questions/75613656/openai-chatgpt-gpt-3-5-turbo-api-how-to-access-the-message-content) – Rok Benko Mar 21 '23 at 09:24
  • Oups, I wrongly cast for duplicate. The one linked by Rok Benko seems really accurate – Elikill58 Apr 26 '23 at 06:35
  • Maybe this article can help you https://onlinecode.org/php-chatgpt-curl-chatgpt-api-using-php/ – JON Apr 27 '23 at 05:13

2 Answers2

4

Ah... I see the issue... Leaving this answer here if anyone else has the same issue:

There are two distinct parameters, "message" and "messages". I didn't notice the singluar / plural in the error message.

Corrected code is here:

// Define messages
$messages = array();
$message = array();
$message["role"] = "user";
$message["content"] = "Hello future overlord!";
$messages[] = $message;

// Define data
$data = array();
$data["model"] = "gpt-3.5-turbo";
$data["messages"] = $messages;
$data["max_tokens"] = 50;

Thanks everyone above for the comments.

Bangkokian
  • 6,548
  • 3
  • 19
  • 26
-1
<?php
$apiKey = "API KEY";
$model = "text-davinci-003";
$prompt = $_POST['prompt'];
$temperature = 0.7;
$maxTokens = 256;
$topP = 1;
$frequencyPenalty = 0;
$presencePenalty = 0;

$data = array(
    'model' => $model,
    'prompt' => $prompt,
    'temperature' => $temperature,
    'max_tokens' => $maxTokens,
    'top_p' => $topP,
    'frequency_penalty' => $frequencyPenalty,
    'presence_penalty' => $presencePenalty
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.openai.com/v1/completions");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . $apiKey));

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
} else {
    $jsonResponse = json_decode($response, true);
    $generatedText = '';
    var_dump($jsonResponse);die();
    if (isset($jsonResponse['choices']) && count($jsonResponse['choices']) > 0 && isset($jsonResponse['choices'][0]['text'])) {
        $generatedText = $jsonResponse['choices'][0]['text'];
    } else {
        $generatedText = 'No response generated.';
    }
  
    $sentences = preg_split('/(?<=[.?!])\s+(?=[a-z])/i', $generatedText);
    $numSentences = count($sentences);
    $paragraphs = array();
    $curParagraph = '';
    for ($i = 0; $i < $numSentences; $i++) {
        $curParagraph .= $sentences[$i] . ' ';
        if (($i + 1) % 3 == 0) {
            array_push($paragraphs, $curParagraph);
            $curParagraph = '';
        }
    }
    if ($curParagraph != '') {
        array_push($paragraphs, $curParagraph);
    }
    foreach ($paragraphs as $paragraph) {
        echo "<p>" . trim($paragraph) . "</p>" . "<br>";
    }
}

curl_close($ch);
?>
Yasas Malinga
  • 29
  • 1
  • 4
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 02 '23 at 09:49