当前位置:   article > 正文

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

chatgpt 3.5 接口

目录

 

一、介绍

 二、官方使用案例

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


一、介绍

https://platform.openai.com/docs/models/overview

 二、官方使用案例

  1. const { Configuration, OpenAIApi } = require("openai");
  2. const configuration = new Configuration({
  3. apiKey: process.env.OPENAI_API_KEY,
  4. });
  5. const openai = new OpenAIApi(configuration);
  6. const completion = await openai.createChatCompletion({
  7. model: "gpt-3.5-turbo",
  8. messages: [{role: "user", content: "Hello world"}],
  9. });
  10. console.log(completion.data.choices[0].message);

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

  1. let openAiType = 2 //1达芬奇 2turbo
  2. const chatAdd = async (req, res) => {
  3. const {
  4. talkId = '',
  5. name = '',
  6. messageType = '1',
  7. message = '',
  8. modelType = '1',
  9. promptType = '1',
  10. isNeedContext = true,
  11. } = req.body
  12. let prompt = ''
  13. let messages = []
  14. if (openAiType === 1) {
  15. if (promptType === '1') {
  16. if (currentChatList.length > 0 && isNeedContext === true) {
  17. let shotChatList = currentChatList
  18. if (currentChatList.length > 6) {
  19. shotChatList = currentChatList.slice(currentChatList.length - 6)
  20. }
  21. shotChatList.forEach((item) => {
  22. let { messageType, message } = item
  23. if (messageType === '1') {
  24. prompt += `YOU:${message}\n`
  25. } else if (messageType === '2') {
  26. //message = encodeURIComponent(message)
  27. prompt += `AI:${message}\n`
  28. }
  29. })
  30. }
  31. prompt += `YOU:${message}\nAI:`
  32. } else if (promptType === '2') {
  33. if (currentChatList.length > 0 && isNeedContext === true) {
  34. let shotChatList = currentChatList
  35. if (currentChatList.length > 6) {
  36. shotChatList = currentChatList.slice(currentChatList.length - 6)
  37. }
  38. shotChatList.forEach((item) => {
  39. const { messageType, message } = item
  40. if (messageType === '1') {
  41. prompt += `\n/* Command: ${message} */\n`
  42. } else if (messageType === '2') {
  43. //message = encodeURIComponent(message)
  44. prompt += `${message}\n`
  45. }
  46. })
  47. }
  48. 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`
  49. }
  50. } else if (openAiType === 2) {
  51. if (currentChatList.length > 0 && isNeedContext === true) {
  52. let shotChatList = currentChatList
  53. if (currentChatList.length > 6) {
  54. shotChatList = currentChatList.slice(currentChatList.length - 6)
  55. }
  56. shotChatList.forEach((item) => {
  57. let { messageType, message } = item
  58. if (messageType === '1') {
  59. messages = [...messages, { role: 'user', content: message }]
  60. } else if (messageType === '2') {
  61. messages = [...messages, { role: 'assistant', content: message }]
  62. }
  63. })
  64. }
  65. messages = [...messages, { role: 'user', content: message }]
  66. }
  67. let completion
  68. let historyAccountIndex = currentAccountIndex
  69. let errorData = ''
  70. try {
  71. if (openAiType === 1) {
  72. let hooks = [
  73. {
  74. value: '1',
  75. lable: 'text-davinci-003',
  76. },
  77. {
  78. value: '2',
  79. lable: 'code-davinci-002',
  80. },
  81. ]
  82. let resultIndex = hooks.findIndex((item) => item.value === modelType)
  83. let model = 'text-davinci-003'
  84. if (resultIndex >= 0) {
  85. model = hooks[resultIndex].lable
  86. }
  87. const completionRes = await openai
  88. .createCompletion({
  89. model,
  90. // prompt:
  91. // 'YOU:你好\n你好。很高兴见到你。\nYOU:你叫什么名字\n我叫小爱。很高兴见到你!\nYOU:介绍一下元宵节\n',
  92. prompt,
  93. max_tokens: 2048,
  94. })
  95. .catch((err) => {
  96. errorData = err
  97. if (err?.response?.data?.error?.type === 'insufficient_quota') {
  98. console.log('配额不足,已经自动更新账号')
  99. const hostname = os.hostname()
  100. if (hostname !== 'LAPTOP-4KDIA4A3') {
  101. customSendEmail({
  102. subject: '配额不足,已经自动更新账号',
  103. html: `historyAccountIndex:${historyAccountIndex},currentAccountIndex: ${currentAccountIndex}`,
  104. })
  105. }
  106. changeOpenAI()
  107. }
  108. })
  109. completion = completionRes.data
  110. } else if (openAiType === 2) {
  111. const completionRes = await openai
  112. .createChatCompletion({
  113. model: 'gpt-3.5-turbo',
  114. messages,
  115. })
  116. .catch((err) => {
  117. errorData = err
  118. if (err?.response?.data?.error?.type === 'insufficient_quota') {
  119. console.log('配额不足,已经自动更新账号')
  120. const hostname = os.hostname()
  121. if (hostname !== 'LAPTOP-4KDIA4A3') {
  122. customSendEmail({
  123. subject: '配额不足,已经自动更新账号',
  124. html: `historyAccountIndex:${historyAccountIndex},currentAccountIndex: ${currentAccountIndex}`,
  125. })
  126. }
  127. changeOpenAI()
  128. }
  129. })
  130. completion = completionRes.data
  131. }
  132. } catch (error) {
  133. res.send({
  134. code: 200,
  135. data: {
  136. historyAccountIndex,
  137. currentAccountIndex,
  138. isRobotBusy: true,
  139. errorData,
  140. },
  141. message: '失败-机器人无应答【1】',
  142. })
  143. return
  144. }
  145. if (
  146. Array.isArray(completion.choices) &&
  147. completion.choices.length > 0 &&
  148. (completion.choices[0].text ||
  149. (completion.choices[0].message &&
  150. completion.choices[0].message.content))
  151. ) {
  152. const values = []
  153. let robotMessage
  154. if (openAiType === 1) {
  155. robotMessage = completion.choices[0].text
  156. robotMessage = robotMessage.replace(/\n/, '')
  157. } else if (openAiType === 2) {
  158. robotMessage = completion.choices[0].message.content
  159. robotMessage = robotMessage.replace(/\n/, '').replace(/\n/, '')
  160. }
  161. //robotMessage = decodeURIComponent(robotMessage)
  162. values.push(`(
  163. '${uid}',
  164. '${talkId}',
  165. '${name}',
  166. '${messageType}',
  167. '${message}',
  168. '${now}',
  169. '${now}',
  170. '新增'
  171. )`)
  172. const uidForRobot = uuidv4()
  173. values.push(`(
  174. '${uidForRobot}',
  175. '${talkId}',
  176. 'robot',
  177. '2',
  178. '${robotMessage}',
  179. '${now + 1000}',
  180. '${now + 1000}',
  181. '新增'
  182. )`)
  183. const valuesStr = values.join(',')
  184. let err = await runSql(
  185. `INSERT INTO chat (
  186. uid,
  187. talkId,
  188. name,
  189. messageType,
  190. message,
  191. createTime,
  192. updateTime,
  193. remarks
  194. )
  195. VALUES ${valuesStr}`
  196. )
  197. if (err) {
  198. res.send({
  199. code: 400,
  200. data: {
  201. err: err.stack,
  202. },
  203. message: '添加失败',
  204. })
  205. } else {
  206. await refreshRedis({ tableName: 'chat' })
  207. res.send({
  208. code: 200,
  209. data: {
  210. robotMessage,
  211. },
  212. message: '添加成功',
  213. })
  214. }
  215. } else {
  216. res.send({
  217. code: 400,
  218. data: {
  219. currentAccountIndex,
  220. completion,
  221. },
  222. message: '失败-机器人无应答【2】',
  223. })
  224. }
  225. }

参考链接:

https://chat.xutongbao.top

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/290462
推荐阅读
相关标签
  

闽ICP备14008679号