我正在尝试调用新发布的gpt-3.5-turbo
模型的API,并编写了以下代码,该代码应将查询(通过$query
变量)发送到API,然后从API的响应消息中提取内容。
但每次调用都得到null响应。有什么想法可以告诉我哪里做错了?
$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。如果您无法弄清楚如何修复这个问题,请发送电子邮件到[email protected],并附上您需要帮助的相关代码。)"
。
将这个…
$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
,OpenAI API将返回以下完成内容:
string(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);?>