我正在尝试执行对新发布的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;
1条答案
按热度按时间slhcrj9b1#
您得到
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.)"
.改变这个...
......到这个。
工作示例
如果您在CMD中运行
php test.php
,OpenAI API将返回以下完成:字符串(40)"
英国的首都是伦敦。"