1
0
Code Issues Pull Requests Projects Releases Wiki Activity GitHub Gitee
Files
tools/tools/ChatGPT/chatgpt35.js
2023-05-31 13:13:57 +08:00

85 lines
2.3 KiB
JavaScript

// 尚未是否能用
const axios = require('axios');
// 设置OpenAI API的访问密钥
const apiKey = 'YOUR_API_KEY'; // 替换为你的OpenAI API密钥
// 设置对话的初始参数
const initialMessage = '你好'; // 设置对话的起始消息
let conversationId = null; // 保存对话的ID
// 发送对话请求到OpenAI API
async function sendMessage(message) {
try {
const response = await axios.post(
'https://api.openai.com/v1/chat/completions',
{
messages: [
{ role: 'system', content: 'system' },
{ role: 'user', content: message },
],
model: 'gpt-3.5-turbo',
conversation_id: conversationId,
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
}
);
// 提取OpenAI API的响应
const { choices, id } = response.data;
const { role, content } = choices[0];
// 更新对话的ID
if (!conversationId) {
conversationId = id;
}
// 返回模型生成的回复
return content;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
// 初始化对话
async function initConversation() {
try {
const response = await sendMessage(initialMessage);
console.log('AI:', response);
} catch (error) {
console.error('Error:', error);
throw error;
}
}
// 处理用户输入和模型回复的逻辑
async function handleUserInput(input) {
// 发送用户的输入并获取模型的回复
const reply = await sendMessage(input);
// 输出模型的回复
console.log('AI:', reply);
// 返回模型生成的回复
return reply;
}
// 启动应用程序
async function startApp() {
// 初始化对话
await initConversation();
// 调用示例
const userInput = '你好'; // 通过函数调用输入用户的消息
const reply = await handleUserInput(userInput);
console.log('AI回复:', reply);
}
// 启动应用程序
startApp();