我正在尝试执行对新发布的gpt-3.5-turbo
模型的API调用,并具有以下代码,该代码应该向API发送查询(通过$query
变量),然后从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主体无法解析。
您会得到以下错误:"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 [email protected]
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
);
工作示例
如果您在CMD中运行php test.php
,OpenAI API将返回以下完成:
字符串(40)"
英国的首都是伦敦。"
- 测试. 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);
?>
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。