ChatGPT学习心得一(使用node+react做了一个案例)

项目地址

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.body
  const 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 = currentChatList
          if (currentChatList.length > 10) {
            shotChatList = currentChatList.slice(currentChatList.length - 10)
          }
          shotChatList.forEach((item) => {
            let { messageType, message } = item
            if (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 = currentChatList
          if (currentChatList.length > 10) {
            shotChatList = currentChatList.slice(currentChatList.length - 10)
          }          
          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}nn/* Command: ${message} */n`
      }

      let completion
      try {
        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,
        })
        completion = completionRes.data
      } catch (error) {
        res.send({
          code: 200,
          data: {
            isRobotBusy: true,
          },
          message: '失败-机器人无应答',
        })
        return
      }

      if (
        Array.isArray(completion.choices) &&
        completion.choices.length > 0 &&
        completion.choices[0].text
      ) {
        const values = []
        let robotMessage = completion.choices[0].text
        robotMessage = robotMessage.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: {
              //isRobotBusy: true,
              prompt,
              robotMessage,
            },
            message: '添加成功',
          })
        }
      } else {
        res.send({
          code: 400,
          data: {},
          message: '失败-机器人无应答',
        })
      }
    } else {
      res.send({
        code: 400,
        data: {},
        message: '失败-参数:message',
      })
    }
  } else {
    res.send({
      code: 400,
      data: {},
      message: '失败-参数:talkId',
    })
  }
}

 


chatGPT 是一款由 OpenAI 开发的聊天机器人模型,它能够模拟人类的语言行为,与用户进行自然的交互。它的名称来源于它所使用的技术—— GPT-3架构,即生成式语言模型的第3代。
chatGPT的核心技术是 GPT-3 架构。它通过使用大量的训练数据来模拟人类的语言行为,并通过语法和语义分析,生成人类可以理解的文本。它可以根据上下文和语境,提供准确和恰当的回答,并模拟多种情绪和语气。这样,就可以让用户在与机器交互时,感受到更加真实和自然的对话体验。
chatGPT 的应用场景也很广泛。它可以用于处理多种类型的对话,包括对话机器人、问答系统和客服机器人等。它还可以用于各种自然语言处理任务,比如文本摘要、情感分析和信息提取等。例如,在一个问答系统中,chatGPT可以提供准确的答案,解决用户的疑惑;在一个客服机器人中,它可以帮助用户解决问题,提供更好的服务体验。
在未来,chatGPT 的发展方向将会更加多元。它可能会引入更多的语言模型和深度学习技术,使得它的性能更加优秀。它也可能会拓展到更多的应用场景,为更多的人群提供服务。例如,它可能会进一步拓展到更多的语言领域,支持更多的语言;也可能会更加灵活,可以根据不同的目标来进行微调,适应不同的场景和需求。
此外,chatGPT 也面临着一些风险和挑战。其中,最主要的问题是隐私和安全。由于 chatGPT 涉及到大量的个人信息,因此如果不加以保护,就有可能被黑客攻击和泄露。此外,由于 chatGPT 模拟人类的语言行为,因此如果不加以控制,它也可能会发生一些不良信息的传播。
另一方面,在技术方面,chatGPT 也面临着一些挑战。由于它依赖于深度学习和大规模数据,因此如果数据质量不高或者模型不稳定,它的性能就会受到影响。此外,由于它所处理的是自然语言,因此它也需要面对语言多样性和变化性等问题。
总之,chatGPT 是一款先进的聊天机器人模型,它可以为各种应用场景提供智能化的对话功能。通过它,可以让用户在与机器交互时,感受到更加真实和自然的对话体验。在未来,它将会更加成熟,为人类带来更多的便利。

聪明的你应该已经发现了,这篇文章是由chatAI自己生成的。
 

 

 

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>