API OpenAI ChatGPT (gpt-3.5-turbo): почему я получаю ответ NULL?
Я пытаюсь выполнить вызовы API для новой версииgpt-3.5-turbo
модель и иметь следующий код, который должен отправить запрос (через$query
переменная) в API, а затем извлечь содержимое ответного сообщения из API.
Но я получаю нулевые ответы на каждый вызов. Любые идеи, что я сделал неправильно?
$ch = curl_init();
$query = "What is the capital city of England?";
$url = 'https://api.openai.com/v1/chat/completions';
$api_key = 'sk-**************************************';
$post_fields = [
"model" => "gpt-3.5-turbo",
"messages" => ["role" => "user","content" => $query],
"max_tokens" => 500,
"temperature" => 0.8
];
$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
$response = json_decode($result);
$response = $response->choices[0]->message[0]->content;
1 ответ
Причина, по которой вы получаетеNULL
ответ связан с тем, что тело JSON не может быть проанализировано.
Вы получаете следующую ошибку:"We could not parse the JSON body of your request. (HINT: This likely means you aren't using your HTTP library correctly. The OpenAI API expects a JSON payload, but what was sent was not valid JSON. If you have trouble figuring out how to fix this, please send an email to support@openai.com and include any relevant code you'd like help with.)"
.
Изменить это...
$post_fields = [
"model" => "gpt-3.5-turbo",
"messages" => ["role" => "user","content" => $query],
"max_tokens" => 12,
"temperature" => 0
];
...к этому.
$post_fields = array(
"model" => "gpt-3.5-turbo",
"messages" => array(
array(
"role" => "user",
"content" => $query
)
),
"max_tokens" => 12,
"temperature" => 0
);
Рабочий пример
Если вы запуститеphp test.php
в CMD API OpenAI вернет следующее завершение:
строка(40) "
Столица Англии — Лондон».
test.php
<?php
$ch = curl_init();
$url = 'https://api.openai.com/v1/chat/completions';
$api_key = 'sk-xxxxxxxxxxxxxxxxxxxx';
$query = 'What is the capital city of England?';
$post_fields = array(
"model" => "gpt-3.5-turbo",
"messages" => array(
array(
"role" => "user",
"content" => $query
)
),
"max_tokens" => 12,
"temperature" => 0
);
$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
$response = json_decode($result);
var_dump($response->choices[0]->message->content);
?>