|
免费chatGPT体验入口:
http://chat.xutongbao.top/
目录
一、介绍
二、官方使用案例
三、我写的案例(撑持上下文)
<hr/>
一、介绍
https://platform.openai.com/docs/models/overview
二、官方使用案例
const { Configuration, OpenAIApi } = require(”openai”);
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const completion = await openai.createChatCompletion({
model: ”gpt-3.5-turbo”,
messages: [{role: ”user”, content: ”Hello world”}],
});
console.log(completion.data.choices[0].message);
三、我写的案例(撑持上下文)
let openAiType = 2 //1达芬奇 2turbo
const chatAdd = async (req, res) => {
const {
talkId = '',
name = '',
messageType = '1',
message = '',
modelType = '1',
promptType = '1',
isNeedContext = true,
} = req.body
let prompt = ''
let messages = []
if (openAiType === 1) {
if (promptType === '1') {
if (currentChatList.length > 0 && isNeedContext === true) {
let shotChatList = currentChatList
if (currentChatList.length > 6) {
shotChatList = currentChatList.slice(currentChatList.length - 6)
}
shotChatList.forEach((item) => {
let { messageType, message } = item
if (messageType === '1') {
prompt += `YOU:${message}\n`
} else if (messageType === '2') {
//message = encodeURIComponent(message)
prompt += `AI:${message}\n`
}
})
}
prompt += `YOU:${message}\nAI:`
} else if (promptType === '2') {
if (currentChatList.length > 0 && isNeedContext === true) {
let shotChatList = currentChatList
if (currentChatList.length > 6) {
shotChatList = currentChatList.slice(currentChatList.length - 6)
}
shotChatList.forEach((item) => {
const { messageType, message } = item
if (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 <script> injection. Written for Chrome. */\n/* Command: Add ”Hello World”, by adding an HTML DOM node */\nvar helloWorld = document.createElement('div');\nhelloWorld.innerHTML = 'Hello World';\ndocument.body.appendChild(helloWorld);\n/* Command: Clear the page. */\nwhile (document.body.firstChild) {\n document.body.removeChild(document.body.firstChild);\n}\n\n/* Command: ${message} */\n`
}
} else if (openAiType === 2) {
if (currentChatList.length > 0 && isNeedContext === true) {
let shotChatList = currentChatList
if (currentChatList.length > 6) {
shotChatList = currentChatList.slice(currentChatList.length - 6)
}
shotChatList.forEach((item) => {
let { messageType, message } = item
if (messageType === '1') {
messages = [...messages, { role: 'user', content: message }]
} else if (messageType === '2') {
messages = [...messages, { role: 'assistant', content: message }]
}
})
}
messages = [...messages, { role: 'user', content: message }]
}
let completion
let historyAccountIndex = currentAccountIndex
let errorData = ''
try {
if (openAiType === 1) {
let hooks = [
{
value: '1',
lable: 'text-davinci-003',
},
{
value: '2',
lable: 'code-davinci-002',
},
]
let resultIndex = hooks.findIndex((item) => item.value === modelType)
let model = 'text-davinci-003'
if (resultIndex >= 0) {
model = hooks[resultIndex].lable
}
const completionRes = await openai
.createCompletion({
model,
// prompt:
// 'YOU:你好\n你好。很高兴见到你。\nYOU:你叫什么名字\n我叫小爱。很高兴见到你!\nYOU:介绍一下元宵节\n',
prompt,
max_tokens: 2048,
})
.catch((err) => {
errorData = err
if (err?.response?.data?.error?.type === 'insufficient_quota') {
console.log('配额不足,已经自动更新账号')
const hostname = os.hostname()
if (hostname !== 'LAPTOP-4KDIA4A3') {
customSendEmail({
subject: '配额不足,已经自动更新账号',
html: `historyAccountIndex:${historyAccountIndex},currentAccountIndex: ${currentAccountIndex}`,
})
}
changeOpenAI()
}
})
completion = completionRes.data
} else if (openAiType === 2) {
const completionRes = await openai
.createChatCompletion({
model: 'gpt-3.5-turbo',
messages,
})
.catch((err) => {
errorData = err
if (err?.response?.data?.error?.type === 'insufficient_quota') {
console.log('配额不足,已经自动更新账号')
const hostname = os.hostname()
if (hostname !== 'LAPTOP-4KDIA4A3') {
customSendEmail({
subject: '配额不足,已经自动更新账号',
html: `historyAccountIndex:${historyAccountIndex},currentAccountIndex: ${currentAccountIndex}`,
})
}
changeOpenAI()
}
})
completion = completionRes.data
}
} catch (error) {
res.send({
code: 200,
data: {
historyAccountIndex,
currentAccountIndex,
isRobotBusy: true,
errorData,
},
message: '掉败-机器人无应答【1】',
})
return
}
if (
Array.isArray(completion.choices) &&
completion.choices.length > 0 &&
(completion.choices[0].text ||
(completion.choices[0].message &&
completion.choices[0].message.content))
) {
const values = []
let robotMessage
if (openAiType === 1) {
robotMessage = completion.choices[0].text
robotMessage = robotMessage.replace(/\n/, '')
} else if (openAiType === 2) {
robotMessage = completion.choices[0].message.content
robotMessage = robotMessage.replace(/\n/, '').replace(/\n/, '')
}
//robotMessage = decodeURIComponent(robotMessage)
values.push(`(
'${uid}',
'${talkId}',
'${name}',
'${messageType}',
'${message}',
'${now}',
'${now}',
'新增'
)`)
const uidForRobot = uuidv4()
values.push(`(
'${uidForRobot}',
'${talkId}',
'robot',
'2',
'${robotMessage}',
'${now + 1000}',
'${now + 1000}',
'新增'
)`)
const valuesStr = values.join(',')
let err = await runSql(
`INSERT INTO chat (
uid,
talkId,
name,
messageType,
message,
createTime,
updateTime,
remarks
)
VALUES ${valuesStr}`
)
if (err) {
res.send({
code: 400,
data: {
err: err.stack,
},
message: '添加掉败',
})
} else {
await refreshRedis({ tableName: 'chat' })
res.send({
code: 200,
data: {
robotMessage,
},
message: '添加成功',
})
}
} else {
res.send({
code: 400,
data: {
currentAccountIndex,
completion,
},
message: '掉败-机器人无应答【2】',
})
}
}
参考链接:
ChatGPT学习心得一(使用node+react做了一个案例)_徐同保的博客-CSDN博客
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
×
|