给一段html用的js调用chatgpt对话api的v1chatcompletions接口的demo代码EventStream模式返回逐字写入文本框
以下是一个使用JavaScript调用ChatGPT对话API的示例代码,使用EventStream模式返回逐字写入文本框:
<!DOCTYPE html>
<html>
<head>
<title>ChatGPT API Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>ChatGPT API Demo</h1>
<div>
<label for="input">User:</label>
<input type="text" id="input">
</div>
<div>
<label for="output">Chatbot:</label>
<textarea id="output" rows="10"></textarea>
</div>
<button id="submit">Submit</button>
<script>
const input = document.getElementById('input');
const output = document.getElementById('output');
const submit = document.getElementById('submit');
submit.addEventListener('click', () => {
const text = input.value;
input.value = '';
output.value += 'User: ' + text + '\n';
const params = {
prompt: text,
max_tokens: 50,
temperature: 0.7,
completion: {
stream: true,
stop: '\n'
}
};
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
};
fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: headers,
body: JSON.stringify(params)
})
.then(response => response.body)
.then(stream => {
const reader = stream.getReader();
let chunks = '';
reader.read().then(function processText({done, value}) {
if (done) {
output.value += 'Chatbot: ' + chunks + '\n';
return;
}
chunks += value;
output.value += 'Chatbot: ' + chunks + '\n';
return reader.read().then(processText);
});
})
.catch(error => console.error(error));
});
</script>
</body>
</html>
在这个示例中,我们首先获取了输入文本框、输出文本框和提交按钮的DOM元素。然后,我们在点击提交按钮时获取输入文本框的值,并将其清空。接下来,我们使用ChatGPT API需要的参数创建一个对象,这里我们使用了一个包含prompt、max_tokens、temperature和completion属性的对象。
其中,prompt属性是用户输入的文本,max_tokens是生成的文本的最大数量,temperature是生成文本的随机度量,completion属性是一个包含stream和stop属性的对象。stream属性被设置为true,表示我们希望使用EventStream模式,stop属性被设置为换行符,表示我们希望ChatGPT API在输出完整个句子后停止生成文本。
接下来,我们使用fetch函数向ChatGPT API发送请求。我们在请求头中设置了Content-Type和Authorization属性,其中Authorization属性是我们在OpenAI网站上获得的API密钥。
在收到响应后,我们使用response.body获取EventStream对象,在.then中我们使用getReader方法获取一个Reader对象,该对象允许我们逐块读取EventStream对象的内容。
在读取EventStream对象的内容时,我们使用递归调用processText函数,该函数会将EventStream对象的内容逐字添加到输出文本框中。当读取完成时,我们添加Chatbot前缀并将结果写入输出文本框的末尾。
请注意,在实际使用ChatGPT API时,需要确保使用的API密钥和请求参数符合OpenAI的使用政策和安全最佳实践。此外,我们也需要对用户输入进行适当的验证和处理,以确保应用程序的安全性和可用性。
原文地址: https://www.cveoy.top/t/topic/L7C 著作权归作者所有。请勿转载和采集!