我使用 chatGBT API,php 代码运行良好。但是,当我想将查询打印到屏幕上时,我得到了未定义。
开发者控制台显示响应如下
我用来将输出打印到屏幕的javascript代码如下。
<script>
const input = document.querySelector('.askMe');
const button = document.querySelector('.getAnswer');
const textarea = document.querySelector('.answerHere');
var communicator = '';
button.onclick = () => {
var prompt = input.value
if(prompt != ''){
bottomScroll();
//to get server Events
var source = new SSE("myai.php?prompt=" + prompt);
input.value = ''
input.focus()
source.addEventListener('message', function (e) {
if(e.data){
if(e.data != '[DONE]'){
var tokens = JSON.parse(e.data).choices[0].text
textarea.innerHTML += tokens
bottomScroll();
}else{
console.log('Completed');
}
}
})
source.stream()
}
}
function bottomScroll(){
textarea.scrollIntoView(false)
textarea.scrollTo(0, textarea.scrollHeight)
}
</script>
myai.php文件中我的代码如下
$API_KEY = "API-KEY";
$model = 'gpt-3.5-turbo';
$header = [
"Authorization: Bearer " . $API_KEY,
"Content-type: application/json",
];
$temperature = 0.6;
$frequency_penalty = 0;
$presence_penalty= 0;
$prompt = 'Hi ?';
//$messages = array(array('role' => 'assistant','content' => $prompt));
$messages = array(
array(
"role" => "user",
"content" => $prompt
)
);
//Turbo model
$isTurbo = true;
$url = "https://api.openai.com/v1/chat/completions";
$params = json_encode([
"messages" => $messages,
"model" => $model,
"temperature" => $temperature,
"max_tokens" => 1024,
"frequency_penalty" => $frequency_penalty,
"presence_penalty" => $presence_penalty,
"stream" => true
]);
$curl = curl_init($url);
$options = [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => $header,
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_WRITEFUNCTION => function($curl, $data) {
//echo $curl;
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($httpCode != 200) {
$r = json_decode($data);
echo 'data: {"error": "[ERROR]","message":"'.$r->error->message.'"}' . PHP_EOL;
}else{
echo $data;
echo PHP_EOL;
ob_flush();
flush();
return strlen($data);
}
},
];
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
if ($response === false) {
echo 'data: {"error": "[ERROR]","message":"'.curl_error($curl).'"}' . PHP_EOL;
}else{
}
为什么它根据这些条件给出未定义的输出以及解决方案是什么。你能帮帮我吗?
我认为我遇到的错误是在 myai.php 文件的
$options
部分。但我不确定。