使用OpenAI API调用gpt-3.5-turbo时出现undefined错误求助
OpenAI API gpt-3.5-turbo调用出现undefined错误排查
问题背景
切换到gpt-3.5-turbo的API语法后,运行代码输出undefined,需排查原因。
错误信息
PS C:\Demo> node index.js undefined
运行代码
import { Configuration, OpenAIApi } from "openai"; const configuration = new Configuration({ organization: "Placeholder", apiKey: "Placeholder" }); const openai = new OpenAIApi(configuration); const completion = await openai.createChatCompletion({ // Functions must be /v1/chat/completions compatible: model: "gpt-3.5-turbo", messages: [ {role: "user", content: "How are you today?"}, ] }); console.log(completion.data.choices[0].text); // print text response from response object
返回的Completion对象
{ status: 200, statusText: 'OK', headers: { date: 'Sat, 29 Jul 2023 04:47:38 GMT', 'content-type': 'application/json', 'content-length': '492', connection: 'close', 'access-control-allow-origin': '*', 'cache-control': 'no-cache, must-revalidate', 'openai-model': 'gpt-3.5-turbo-0613', 'openai-organization': 'user-kkvsk8yyp8b4vxwiot1omana', 'openai-processing-ms': '1666', 'openai-version': '2020-10-01', 'strict-transport-security': 'max-age=15724800; includeSubDomains', 'x-ratelimit-limit-requests': '200', 'x-ratelimit-limit-tokens': '40000', 'x-ratelimit-remaining-requests': '197', 'x-ratelimit-remaining-tokens': '39978', 'x-ratelimit-reset-requests': '15m0.985s', 'x-ratelimit-reset-tokens': '33ms', 'x-request-id': '97ffedd744caa7b206f878d2200c90a5', 'cf-cache-status': 'DYNAMIC', server: 'cloudflare', 'cf-ray': '7ee2b98bc8b0d9d1-MIA', 'alt-svc': 'h3=":443"; ma=86400' }, config: { transitional: { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }, adapter: [Function: httpAdapter], transformRequest: [ [Function: transformRequest] ], transformResponse: [ [Function: transformResponse] ], timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, maxBodyLength: -1, validateStatus: [Function: validateStatus], headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'User-Agent': 'OpenAI/NodeJS/3.3.0', Authorization: 'Bearer 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', 'OpenAI-Organization': 'org-UfIKVGWEJyAhjwRVK9wrMBRZ', 'Content-Length': 85 }, method: 'post', data: '{"model":"gpt-3.5-turbo","messages":[{"role":"user","content":"How are you today?"}]}', url: 'https://api.openai.com/v1/chat/completions' }, request: <ref *1> ClientRequest { _events: [Object: null prototype] { abort: [Function (anonymous)], aborted: [Function (anonymous)], connect: [Function (anonymous)], error: [Function (anonymous)], socket: [Function (anonymous)], timeout: [Function (anonymous)], finish: [Function: requestOnFinish] }, _eventsCount: 7, _maxListeners: undefined, outputData: [], outputSize: 0, writable: true, destroyed: false, _last: true, chunkedEncoding: false, shouldKeepAlive: false, maxRequestsOnConnectionReached: false, _defaultKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: false, _removedConnection: false, _removedContLen: false, _removedTE: false, strictContentLength: false, _contentLength: 85, _hasBody: true, _trailer: '', finished: true, _headerSent: true, _closed: false, socket: TLSSocket { _tlsOptions: [Object], _secureEstablished: true, _securePending: false, _newSessionPending: false, _controlReleased: true, secureConnecting: false, _SNICallback: null, servername: 'api.openai.com', alpnProtocol: false, authorized: true, authorizationError: null, encrypted: true, _events: [Object: null prototype], _eventsCount: 10, connecting: false, _hadError: false, _parent: null, _host: 'api.openai.com', _closeAfterHandlingError: false, _readableState: [ReadableState], _maxListeners: undefined, _writableState: [WritableState], allowHalfOpen: false, _sockname: null, _pendingData: null, _pendingEncoding: '', server: undefined, _server: null, ssl: [TLSWrap], _requestCert: true, _rejectUnauthorized: true, parser: null, _httpMessage: [Circular *1], [Symbol(res)]: [TLSWrap], [Symbol(verified)]: true, [Symbol(pendingSession)]: null, [Symbol(async_id_symbol)]: 10, [Symbol(kHandle)]: [TLSWrap], [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: null, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(kCapture)]: false, [Symbol(kSetNoDelay)]: false, [Symbol(kSetKeepAlive)]: true, [Symbol(kSetKeepAliveInitialDelay)]: 60, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0, [Symbol(connect-options)]: [Object] }, _header: 'POST /v1/chat/completions HTTP/1.1\r\n' + 'Accept: application/json, text/plain, */*\r\n' + 'Content-Type: application/json\r\n' + 'User-Agent: OpenAI/NodeJS/3.3.0\r\n' + 'Authorization: Bearer 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\r\n' + 'OpenAI-Organization: org-UfIKVGWEJyAhjwRVK9wrMBRZ\r\n' + 'Content-Length: 85\r\n' + 'Host: api.openai.com\r\n' + 'Connection: close\r\n' + '\r\n', _keepAliveTimeout: 0, _onPendingData: [Function: nop], agent: Agent { _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, defaultPort: 443, protocol: 'https:', options: [Object: null prototype], requests: [Object: null prototype] {}, sockets: [Object: null prototype], freeSockets: [Object: null prototype] {}, keepAliveMsecs: 1000, keepAlive: false, maxSockets: Infinity, maxFreeSockets: 256, scheduling: 'lifo', maxTotalSockets: Infinity, totalSocketCount: 1, maxCachedSessions: 100, _sessionCache: [Object], [Symbol(kCapture)]: false }, socketPath: undefined, method: 'POST', maxHeaderSize: undefined, insecureHTTPParser: undefined, joinDuplicateHeaders: undefined, path: '/v1/chat/completions', _ended: true, res: IncomingMessage { _readableState: [ReadableState], _events: [Object: null prototype], _eventsCount: 4, _maxListeners: undefined, socket: [TLSSocket], httpVersionMajor: 1, httpVersionMinor: 1, httpVersion: '1.1', complete: true, rawHeaders: [Array], rawTrailers: [], joinDuplicateHeaders: undefined, aborted: false, upgrade: false, url: '', method: null, statusCode: 200, statusMessage: 'OK', client: [TLSSocket], _consuming: false, _dumped: false, req: [Circular *1], responseUrl: 'https://api.openai.com/v1/chat/completions', redirects: [], [Symbol(kCapture)]: false, [Symbol(kHeaders)]: [Object], [Symbol(kHeadersCount)]: 44, [Symbol(kTrailers)]: null, [Symbol(kTrailersCount)]: 0 }, aborted: false, timeoutCb: null, upgradeOrConnect: false, parser: null, maxHeadersCount: null, reusedSocket: false, host: 'api.openai.com', protocol: 'https:', _redirectable: Writable { _writableState: [WritableState], _events: [Object: null prototype], _eventsCount: 3, _maxListeners: undefined, _options: [Object], _ended: true, _ending: true, _redirectCount: 0, _redirects: [], _requestBodyLength: 85, _requestBodyBuffers: [], _onNativeResponse: [Function (anonymous)], _currentRequest: [Circular *1], _currentUrl: 'https://api.openai.com/v1/chat/completions', [Symbol(kCapture)]: false }, [Symbol(kCapture)]: false, [Symbol(kBytesWritten)]: 0, [Symbol(kNeedDrain)]: false, [Symbol(corked)]: 0, [Symbol(kOutHeaders)]: [Object: null prototype] { accept: [Array], 'content-type': [Array], 'user-agent': [Array], authorization: [Array], 'openai-organization': [Array], 'content-length': [Array], host: [Array] }, [Symbol(errored)]: null, [Symbol(kHighWaterMark)]: 16384, [Symbol(kRejectNonStandardBodyWrites)]: false, [Symbol(kUniqueHeaders)]: null }, data: { id: 'chatcmpl-7hW9YTnN96BXLqCsurIMqzCpdD9EJ', object: 'chat.completion', created: 1690606056, model: 'gpt-3.5-turbo-0613', choices: [ [Object] ], usage: { prompt_tokens: 12, completion_tokens: 27, total_tokens: 39 } } }
排查思路与解决方法
核心错误原因:gpt-3.5-turbo的
chat/completions接口返回结构中,对话内容不在text字段,而是嵌套在message.content里。代码中使用的completion.data.choices[0].text是旧版completions接口的写法,因此返回undefined。修复代码:将输出语句修改为:
console.log(completion.data.choices[0].message.content);
- 额外验证步骤:
- 先打印完整的
completion.data.choices[0],确认返回结构:console.log(completion.data.choices[0]); - 检查代码是否在异步函数中执行:
await必须包裹在async函数内,否则会抛出语法错误。若代码未包裹,需补充:async function getChatResponse() { // 原代码所有内容 } getChatResponse();
- 先打印完整的
内容的提问来源于stack exchange,提问作者Volapiik Vyrient
相关产品推荐
相关产品推荐

