ChatGPT学习心得一(使用node+react做了一个案例)
创始人
2024-05-25 19:12:51
0

项目地址

http://chat.xutongbao.top

项目截图

 

 

 

使用技术栈

node+SQLite+redis+nginx+log4js+express+jenkins+cdn+react+antd+react-scrollbars-custom+iconfont+webpack+postman+axios+redux+immutable+npm+yarn+openai等等

官网

https://openai.com/blog/chatgpt/

官方聊天应用

https://chat.openai.com/chat/79014944-0302-45ff-bd25-073803e37216

官方Javascript沙盒应用

https://platform.openai.com/codex-javascript-sandbox

 官方技术文档

https://platform.openai.com/docs/introduction

 

node调用ChatGPT的API

装包:

yarn add openai

获取API Keys:

https://platform.openai.com/docs/api-reference/introduction

 https://platform.openai.com/account/api-keys

 获取Organization ID:

https://platform.openai.com/account/org-settings 

node代码:

const { Configuration, OpenAIApi } = require('openai')const configuration = new Configuration({organization: 'xxx',apiKey: 'xxx',
})
const openai = new OpenAIApi(configuration)//增加
const chatAdd = async (req, res) => {const {talkId = '',name = '',messageType = '1',message = '',modelType = '1',promptType = '1',} = req.bodyconst uid = uuidv4()const now = Date.now()const talkRedis = await redisClient.get('talk')let talkList = JSON.parse(talkRedis)const resultIndex = talkList.findIndex((item) => item.uid === talkId)if (resultIndex >= 0) {if (message && message.trim() !== '') {const chatRedis = await redisClient.get('chat')let chatList = JSON.parse(chatRedis)chatList = Array.isArray(chatList) ? chatList : []let currentChatList = chatList.filter((item) => item.talkId === talkId).sort((a, b) => a.createTime - b.createTime)let prompt = ''if (promptType === '1') {if (currentChatList.length > 0) {let shotChatList = currentChatListif (currentChatList.length > 10) {shotChatList = currentChatList.slice(currentChatList.length - 10)}shotChatList.forEach((item) => {let { messageType, message } = itemif (messageType === '1') {prompt += `YOU:${message}\n`} else if (messageType === '2') {//message = encodeURIComponent(message)prompt += `${message}\n`}})}prompt += `YOU:${message}\n`} else if (promptType === '2') {if (currentChatList.length > 0) {let shotChatList = currentChatListif (currentChatList.length > 10) {shotChatList = currentChatList.slice(currentChatList.length - 10)}          shotChatList.forEach((item) => {const { messageType, message } = itemif (messageType === '1') {prompt += `\n/* Command: ${message} */\n`} else if (messageType === '2') {//message = encodeURIComponent(message)prompt += `${message}\n`}})}prompt += `<|endoftext|>/* I start with a blank HTML page, and incrementally modif it via