3

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!

9
  • 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. Commented Mar 19, 2023 at 7: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. Commented Mar 19, 2023 at 7:37
  • @TangentiallyPerpendicular Yes, but the API requires a JSON string. That's all it accepts.
    – Bangkokian
    Commented Mar 19, 2023 at 7:39
  • Can you change $data["messages"] = $messages; line to $data["messages[]"] = $messages; and try it again?
    – M. Ismail
    Commented Mar 19, 2023 at 7:42
  • 2
    Does this answer your question? OpenAI ChatGPT (gpt-3.5-turbo) API: How to access the message content?
    – Rok Benko
    Commented Mar 21, 2023 at 9:24

2 Answers 2

5

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.

-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);
?>
1
  • 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.
    – Community Bot
    Commented Apr 2, 2023 at 9:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.