NodeJS 尝试使用openai API时出现未定义的错误

lsmepo6l  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(243)

一直在尝试使用openai API。在意识到我使用的是旧版API的语法后,我将其切换到了3. 5版本。现在似乎得到一个未定义的错误。不确定,但我可能又做错了语法方面的事情?对这个问题有什么想法吗?
错误代码:

  1. PS C:\Demo> node index.js
  2. undefined

字符串
代码:

  1. import { Configuration, OpenAIApi } from "openai";
  2. const configuration = new Configuration({
  3. organization: "Placeholder",
  4. apiKey: "Placeholder"
  5. });
  6. const openai = new OpenAIApi(configuration);
  7. const completion = await openai.createChatCompletion({ // Functions must be /v1/chat/completions compatible:
  8. model: "gpt-3.5-turbo",
  9. messages: [
  10. {role: "user", content: "How are you today?"},
  11. ]
  12. });
  13. console.log(completion.data.choices[0].text); // print text response from response object


UPDATE ADDED完成对象:

  1. {
  2. status: 200,
  3. statusText: 'OK',
  4. headers: {
  5. date: 'Sat, 29 Jul 2023 04:47:38 GMT',
  6. 'content-type': 'application/json',
  7. 'content-length': '492',
  8. connection: 'close',
  9. 'access-control-allow-origin': '*',
  10. 'cache-control': 'no-cache, must-revalidate',
  11. 'openai-model': 'gpt-3.5-turbo-0613',
  12. 'openai-organization': 'user-kkvsk8yyp8b4vxwiot1omana',
  13. 'openai-processing-ms': '1666',
  14. 'openai-version': '2020-10-01',
  15. 'strict-transport-security': 'max-age=15724800; includeSubDomains',
  16. 'x-ratelimit-limit-requests': '200',
  17. 'x-ratelimit-limit-tokens': '40000',
  18. 'x-ratelimit-remaining-requests': '197',
  19. 'x-ratelimit-remaining-tokens': '39978',
  20. 'x-ratelimit-reset-requests': '15m0.985s',
  21. 'x-ratelimit-reset-tokens': '33ms',
  22. 'x-request-id': '97ffedd744caa7b206f878d2200c90a5',
  23. 'cf-cache-status': 'DYNAMIC',
  24. server: 'cloudflare',
  25. 'cf-ray': '7ee2b98bc8b0d9d1-MIA',
  26. 'alt-svc': 'h3=":443"; ma=86400'
  27. },
  28. config: {
  29. transitional: {
  30. silentJSONParsing: true,
  31. forcedJSONParsing: true,
  32. clarifyTimeoutError: false
  33. },
  34. adapter: [Function: httpAdapter],
  35. transformRequest: [ [Function: transformRequest] ],
  36. transformResponse: [ [Function: transformResponse] ],
  37. timeout: 0,
  38. xsrfCookieName: 'XSRF-TOKEN',
  39. xsrfHeaderName: 'X-XSRF-TOKEN',
  40. maxContentLength: -1,
  41. maxBodyLength: -1,
  42. validateStatus: [Function: validateStatus],
  43. headers: {
  44. Accept: 'application/json, text/plain, */*',
  45. 'Content-Type': 'application/json',
  46. 'User-Agent': 'OpenAI/NodeJS/3.3.0',
  47. Authorization: 'Bearer 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',
  48. 'OpenAI-Organization': 'org-UfIKVGWEJyAhjwRVK9wrMBRZ',
  49. 'Content-Length': 85
  50. },
  51. method: 'post',
  52. data: '{"model":"gpt-3.5-turbo","messages":[{"role":"user","content":"How are you today?"}]}',
  53. url: 'https://api.openai.com/v1/chat/completions'
  54. },
  55. request: <ref *1> ClientRequest {
  56. _events: [Object: null prototype] {
  57. abort: [Function (anonymous)],
  58. aborted: [Function (anonymous)],
  59. connect: [Function (anonymous)],
  60. error: [Function (anonymous)],
  61. socket: [Function (anonymous)],
  62. timeout: [Function (anonymous)],
  63. finish: [Function: requestOnFinish]
  64. },
  65. _eventsCount: 7,
  66. _maxListeners: undefined,
  67. outputData: [],
  68. outputSize: 0,
  69. writable: true,
  70. destroyed: false,
  71. _last: true,
  72. chunkedEncoding: false,
  73. shouldKeepAlive: false,
  74. maxRequestsOnConnectionReached: false,
  75. _defaultKeepAlive: true,
  76. useChunkedEncodingByDefault: true,
  77. sendDate: false,
  78. _removedConnection: false,
  79. _removedContLen: false,
  80. _removedTE: false,
  81. strictContentLength: false,
  82. _contentLength: 85,
  83. _hasBody: true,
  84. _trailer: '',
  85. finished: true,
  86. _headerSent: true,
  87. _closed: false,
  88. socket: TLSSocket {
  89. _tlsOptions: [Object],
  90. _secureEstablished: true,
  91. _securePending: false,
  92. _newSessionPending: false,
  93. _controlReleased: true,
  94. secureConnecting: false,
  95. _SNICallback: null,
  96. servername: 'api.openai.com',
  97. alpnProtocol: false,
  98. authorized: true,
  99. authorizationError: null,
  100. encrypted: true,
  101. _events: [Object: null prototype],
  102. _eventsCount: 10,
  103. connecting: false,
  104. _hadError: false,
  105. _parent: null,
  106. _host: 'api.openai.com',
  107. _closeAfterHandlingError: false,
  108. _readableState: [ReadableState],
  109. _maxListeners: undefined,
  110. _writableState: [WritableState],
  111. allowHalfOpen: false,
  112. _sockname: null,
  113. _pendingData: null,
  114. _pendingEncoding: '',
  115. server: undefined,
  116. _server: null,
  117. ssl: [TLSWrap],
  118. _requestCert: true,
  119. _rejectUnauthorized: true,
  120. parser: null,
  121. _httpMessage: [Circular *1],
  122. [Symbol(res)]: [TLSWrap],
  123. [Symbol(verified)]: true,
  124. [Symbol(pendingSession)]: null,
  125. [Symbol(async_id_symbol)]: 10,
  126. [Symbol(kHandle)]: [TLSWrap],
  127. [Symbol(lastWriteQueueSize)]: 0,
  128. [Symbol(timeout)]: null,
  129. [Symbol(kBuffer)]: null,
  130. [Symbol(kBufferCb)]: null,
  131. [Symbol(kBufferGen)]: null,
  132. [Symbol(kCapture)]: false,
  133. [Symbol(kSetNoDelay)]: false,
  134. [Symbol(kSetKeepAlive)]: true,
  135. [Symbol(kSetKeepAliveInitialDelay)]: 60,
  136. [Symbol(kBytesRead)]: 0,
  137. [Symbol(kBytesWritten)]: 0,
  138. [Symbol(connect-options)]: [Object]
  139. },
  140. _header: 'POST /v1/chat/completions HTTP/1.1\r\n' +
  141. 'Accept: application/json, text/plain, */*\r\n' +
  142. 'Content-Type: application/json\r\n' +
  143. 'User-Agent: OpenAI/NodeJS/3.3.0\r\n' +
  144. 'Authorization: Bearer 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\r\n' +
  145. 'OpenAI-Organization: org-UfIKVGWEJyAhjwRVK9wrMBRZ\r\n' +
  146. 'Content-Length: 85\r\n' +
  147. 'Host: api.openai.com\r\n' +
  148. 'Connection: close\r\n' +
  149. '\r\n',
  150. _keepAliveTimeout: 0,
  151. _onPendingData: [Function: nop],
  152. agent: Agent {
  153. _events: [Object: null prototype],
  154. _eventsCount: 2,
  155. _maxListeners: undefined,
  156. defaultPort: 443,
  157. protocol: 'https:',
  158. options: [Object: null prototype],
  159. requests: [Object: null prototype] {},
  160. sockets: [Object: null prototype],
  161. freeSockets: [Object: null prototype] {},
  162. keepAliveMsecs: 1000,
  163. keepAlive: false,
  164. maxSockets: Infinity,
  165. maxFreeSockets: 256,
  166. scheduling: 'lifo',
  167. maxTotalSockets: Infinity,
  168. totalSocketCount: 1,
  169. maxCachedSessions: 100,
  170. _sessionCache: [Object],
  171. [Symbol(kCapture)]: false
  172. },
  173. socketPath: undefined,
  174. method: 'POST',
  175. maxHeaderSize: undefined,
  176. insecureHTTPParser: undefined,
  177. joinDuplicateHeaders: undefined,
  178. path: '/v1/chat/completions',
  179. _ended: true,
  180. res: IncomingMessage {
  181. _readableState: [ReadableState],
  182. _events: [Object: null prototype],
  183. _eventsCount: 4,
  184. _maxListeners: undefined,
  185. socket: [TLSSocket],
  186. httpVersionMajor: 1,
  187. httpVersionMinor: 1,
  188. httpVersion: '1.1',
  189. complete: true,
  190. rawHeaders: [Array],
  191. rawTrailers: [],
  192. joinDuplicateHeaders: undefined,
  193. aborted: false,
  194. upgrade: false,
  195. url: '',
  196. method: null,
  197. statusCode: 200,
  198. statusMessage: 'OK',
  199. client: [TLSSocket],
  200. _consuming: false,
  201. _dumped: false,
  202. req: [Circular *1],
  203. responseUrl: 'https://api.openai.com/v1/chat/completions',
  204. redirects: [],
  205. [Symbol(kCapture)]: false,
  206. [Symbol(kHeaders)]: [Object],
  207. [Symbol(kHeadersCount)]: 44,
  208. [Symbol(kTrailers)]: null,
  209. [Symbol(kTrailersCount)]: 0
  210. },
  211. aborted: false,
  212. timeoutCb: null,
  213. upgradeOrConnect: false,
  214. parser: null,
  215. maxHeadersCount: null,
  216. reusedSocket: false,
  217. host: 'api.openai.com',
  218. protocol: 'https:',
  219. _redirectable: Writable {
  220. _writableState: [WritableState],
  221. _events: [Object: null prototype],
  222. _eventsCount: 3,
  223. _maxListeners: undefined,
  224. _options: [Object],
  225. _ended: true,
  226. _ending: true,
  227. _redirectCount: 0,
  228. _redirects: [],
  229. _requestBodyLength: 85,
  230. _requestBodyBuffers: [],
  231. _onNativeResponse: [Function (anonymous)],
  232. _currentRequest: [Circular *1],
  233. _currentUrl: 'https://api.openai.com/v1/chat/completions',
  234. [Symbol(kCapture)]: false
  235. },
  236. [Symbol(kCapture)]: false,
  237. [Symbol(kBytesWritten)]: 0,
  238. [Symbol(kNeedDrain)]: false,
  239. [Symbol(corked)]: 0,
  240. [Symbol(kOutHeaders)]: [Object: null prototype] {
  241. accept: [Array],
  242. 'content-type': [Array],
  243. 'user-agent': [Array],
  244. authorization: [Array],
  245. 'openai-organization': [Array],
  246. 'content-length': [Array],
  247. host: [Array]
  248. },
  249. [Symbol(errored)]: null,
  250. [Symbol(kHighWaterMark)]: 16384,
  251. [Symbol(kRejectNonStandardBodyWrites)]: false,
  252. [Symbol(kUniqueHeaders)]: null
  253. },
  254. data: {
  255. id: 'chatcmpl-7hW9YTnN96BXLqCsurIMqzCpdD9EJ',
  256. object: 'chat.completion',
  257. created: 1690606056,
  258. model: 'gpt-3.5-turbo-0613',
  259. choices: [ [Object] ],
  260. usage: { prompt_tokens: 12, completion_tokens: 27, total_tokens: 39 }
  261. }
  262. }

ebdffaop

ebdffaop1#

的确是语法的问题。忘记为以下对象切换旧版gpt语法:

  1. completion.data.choices[0].text

字符串
的gpt 3.5版本语法:

  1. completion.data.choices[0].message

相关问题