/**
* @param $prefix 文本信息要查询的内容
* @param $apiKey apikey秘钥
* @param int $length 默认20-50之间即可
* @return int
*/
function calculateMaxTokens($prefix, $apiKey, $length = 50)
{
// Create data payload with prompt and desired length
$data = array(
'model' => 'text-davinci-003',
'prompt' => $prefix,
'temperature' => 0.5,
'max_tokens' => $length,
'stop' => '\n',
);
// Set up cURL request with API key
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/completions');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, 320));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
));
//跳过https证书验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//CURL_HTTP_VERSION_1_0 (强制使用 HTTP/1.0)或CURL_HTTP_VERSION_1_1 (强制使用 HTTP/1.1)
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
// Send request and parse response
$response = curl_exec($ch);
// Close cURL session and return result
curl_close($ch);
$responseArr = json_decode($response, true);
$tokens = $responseArr['choices'][0]['finish_reason'] == 'stop' ? count(explode(' ', $responseArr['choices'][0]['text'])) : $length;
return $tokens;
}
网友评论