直接在前端调用 GPT-3 API
Posted nor1take
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了直接在前端调用 GPT-3 API相关的知识,希望对你有一定的参考价值。
〇、效果展示
一、代码:ask.html + app.js
ask.html(内嵌css)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ChatGPT Web Example</title>
<style>
/* 你的 CSS 代码 */
body
font-family: Arial, sans-serif;
padding: 20px;
h1
text-align: center;
margin-bottom: 20px;
#chatbox
border: 1px solid gray;
padding: 10px;
margin-bottom: 20px;
height: 300px;
overflow-y: scroll;
.message
margin-bottom: 10px;
.user-message
text-align: right;
.chatgpt-message
text-align: left;
#inputbox
width: 100%;
padding: 10px;
font-size: 16px;
margin-bottom: 20px;
#submit
background-color: cornflowerblue;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
float: right;
</style>
</head>
<body>
<div id="chatbox">
<!-- 消息列表 -->
</div>
<div id="input-container">
<input id="inputbox" type="text" placeholder="请输入您的问题">
<button id="submit">提交</button>
</div>
<!-- 加载动画元素 -->
<div id="loading" style="display: none;">
<div class="loading-icon"></div>
<div class="loading-text">等待回答...</div>
</div>
</body>
<script src="app.js"></script>
</html>
app.js
const chatboxEl = document.getElementById('chatbox');
const inputEl = document.getElementById('inputbox');
const submitEl = document.getElementById('submit');
const loadingEl = document.getElementById('loading');
submitEl.addEventListener('click', async () =>
const input = inputEl.value;
addMessage(input, 'user');
inputEl.value = '';
// 显示加载动画
loadingEl.style.display = 'block';
// 使用 OpenAI API 获取 ChatGPT 的回答
const response = await getResponseFromAPI(input);
// 隐藏加载动画
loadingEl.style.display = 'none';
addMessage(response, 'chatgpt');
);
function addMessage(text, sender)
const messageEl = document.createElement('div');
messageEl.classList.add('message');
messageEl.classList.add(`$sender-message`);
messageEl.innerHTML = text;
chatboxEl.appendChild(messageEl);
chatboxEl.scrollTop = chatboxEl.scrollHeight;
async function getResponseFromAPI(input)
const endpoint = 'https://api.openai.com/v1/completions';
const apiKey = 'sk-...'; //换成自己的API Key
const prompt = input;
const response = await fetch(endpoint,
method: 'POST',
headers:
'Content-Type': 'application/json',
'Authorization': `Bearer $apiKey`
,
body: JSON.stringify(
model: "text-davinci-003",
prompt,
max_tokens: 100,
n: 1,
stop: null,
temperature: 0.5,
),
);
const result = await response.json();
return result.choices[0].text;
以上是关于直接在前端调用 GPT-3 API的主要内容,如果未能解决你的问题,请参考以下文章