首页 > 其他分享 >OpenAI官方发布ChatGPT API接口gpt-3.5-turbo

OpenAI官方发布ChatGPT API接口gpt-3.5-turbo

时间:2023-03-03 17:23:19浏览次数:52  
标签:completion turbo const currentChatList API 3.5 messageType let message

 

 

目录

 

一、介绍

 二、官方使用案例

 三、我写的案例(支持上下文)


 

一、介绍

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博客

标签:completion,turbo,const,currentChatList,API,3.5,messageType,let,message
From: https://www.cnblogs.com/xutongbao/p/17176356.html

相关文章

  • 调用Android原生@SystemApi、@Hide方法
      系统api.png如上图所示,PackageManager.getPermissionFlags()方法是被@SystemApi注解修饰过的方法,@SystemApi只允许systemapp调用或者用反射方法调用,反射方......
  • ChatGPT开放API,上来就干到最低价,可以人手一个ChatGPT了
    千呼万唤,ChatGPTAPI来了!不仅首发,价格居然还有惊喜,0.002美元/每1000token,并将价格降低90%,直接打了1折。OpenAI官方还表示,gpt-3.5-turbo目前的版本代号是gpt-3.5-turbo-03......
  • 基于API+MQ消息双链路数据同步中间件技术方案
    一、数据同步的背景及意义随着公司业务的发展,业务系统也会变得越来越复杂繁多,业务数据或分散、或冗余于各个业务系统中,增加了数据的管理难度和维护成本。因此,中心......
  • ChatGpt聊天API使用
    昨天ChatGpt发布了聊天API,新增了两个模型,目前还是测试阶段gpt-3.5-turbo功能强大的GPT-3.5模型,专门针对聊天做了优化gpt-3.5-turbo-0301此模型只支持到今年6月份所......
  • flask - fastapi (python 异步API 框架 可以自动生成swagger 文档) 常用示例 以及整合eu
    flask-fastapi(python异步API框架可以自动生成swagger文档)常用示例以及整合eurakanacosflask-fastapi  (python异步API框架 可以自动生成swagger文......
  • 用GoRoutines高性能同时进行多个Api调用
    用GoRoutines高性能同时进行多个Api调用转载请注明来源:https://janrs.com/2023/03/用goroutines同时进行多个api调用/Golang是高效的,非常高效。这种效率在很大程度上要......
  • 关于亚马逊SP-API接口PII申请的一些建议
    网站域名以及你提交的所有资料,不要重复,比如域名,不要你之前申请的时候填写过,被拒绝了,后来申请又填写,这就是资料重复了,资料重复了,你申请公共的亚马逊SP-API开发者PII权限是......
  • 【磐河旅行】之酒店API接口对接实录
    1、项目需求概述:通过对接第三方磐河旅行的酒店API接口实现在我们的APP、微信小程序、H5上可提供用户酒店查询、酒店预订、退订等功能。效果如下图:  2、酒店接口功......
  • JavaSE API
    JavaSEAPI排序java.lang.Comparablejava.lang.Comparatorjava.lang.Object它是所有类型的根父类一个类如果没有显式声明它的父类,这个类的直接父类就是Object理解......
  • Android Studio 友盟api实现apk多渠道打包
    本篇主要给大家介绍利用友盟api实现Android多渠道打包,进入友盟的官网,注册账号,添加对应的应用。1.添加友盟库的依赖2.在manifest.xml中声明appkey,以及渠道占位符3.builde......