gpt4 book ai didi

php - OpenAI ChatGPT (GPT-3.5) API : Why do I get NULL response?

转载 作者:行者123 更新时间:2023-12-02 05:47:00 26 4
gpt4 key购买 nike

我正在尝试对新发布的 gpt-3.5-turbo 模型执行 API 调用,并具有以下代码,该代码应发送查询(通过 $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;

最佳答案

您收到 NULL 响应的原因是无法解析 JSON 正文。

您收到以下错误:“我们无法解析您请求的 JSON 正文。(提示:这可能意味着您没有正确使用 HTTP 库。OpenAI API 需要 JSON 负载,但是什么发送的 JSON 无效。如果您无法弄清楚如何解决此问题,请发送电子邮件至 support@openai.com,并附上您需要帮助的任何相关代码。)”

改变这个...

$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
);

工作示例

如果您在 CMD 中运行 php test.php,OpenAI API 将返回以下完成信息:

string(40) "

The capital city of England is London."

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);
?>

关于php - OpenAI ChatGPT (GPT-3.5) API : Why do I get NULL response?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75614444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com