0

I am trying to create a simple program where I am calling OpenAI API for response to the prompt that will be sent using a text box. I am getting the bellow error. I have changed the Path & API Key while submitting a question

    AxiosError: Request failed with status code 400
            at settle (C:\Path)
            at IncomingMessage.handleStreamEnd (C:\Path)
            at IncomingMessage.emit (node:events:525:35)
            at endReadableNT (node:internal/streams/readable:1359:12)
            at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
          code: 'ERR_BAD_REQUEST',
          config: {
            transitional: {
              silentJSONParsing: true,
              forcedJSONParsing: true,
              clarifyTimeoutError: false
            },
            adapter: [ 'xhr', 'http' ],
            transformRequest: [ [Function: transformRequest] ],
            transformResponse: [ [Function: transformResponse] ],
            timeout: 0,
            xsrfCookieName: 'XSRF-TOKEN',
            xsrfHeaderName: 'X-XSRF-TOKEN',
            maxContentLength: -1,
            maxBodyLength: -1,
            env: { FormData: [Function], Blob: [class Blob] },
            validateStatus: [Function: validateStatus],
            headers: AxiosHeaders {
              Accept: 'application/json, text/plain, */*',
              'Content-Type': 'application/json',
              Authorization: 'Bearer KEY',
              'User-Agent': 'axios/1.4.0',
              'Content-Length': '34',
              'Accept-Encoding': 'gzip, compress, deflate, br'
            },
            method: 'post',
            url: 'https://api.openai.com/v1/completions',
            data: '{"prompt":"hello","max_tokens":60}'
          },
          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: '34',
            _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)]: 16,
              [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/completions HTTP/1.1\r\n' +
              'Accept: application/json, text/plain, */*\r\n' +
              'Content-Type: application/json\r\n' +
              'Authorization: Bearer KEY\r\n' +
              'User-Agent: axios/1.4.0\r\n' +
              'Content-Length: 34\r\n' +
              'Accept-Encoding: gzip, compress, deflate, br\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/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: 400,
              statusMessage: 'Bad Request',
              client: [TLSSocket],
              _consuming: false,
              _dumped: false,
              req: [Circular *1],
              responseUrl: 'https://api.openai.com/v1/completions',
              redirects: [],
              [Symbol(kCapture)]: false,
              [Symbol(kHeaders)]: [Object],
              [Symbol(kHeadersCount)]: 22,
              [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: 34,
              _requestBodyBuffers: [],
              _onNativeResponse: [Function (anonymous)],
              _currentRequest: [Circular *1],
              _currentUrl: 'https://api.openai.com/v1/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],
              authorization: [Array],
              'user-agent': [Array],
              'content-length': [Array],
              'accept-encoding': [Array],
              host: [Array]
            },
            [Symbol(errored)]: null,
            [Symbol(kUniqueHeaders)]: null
          },
          response: {
            status: 400,
            statusText: 'Bad Request',
            headers: AxiosHeaders {
              date: 'Tue, 13 Jun 2023 08:17:18 GMT',
              'content-type': 'application/json; charset=utf-8',
              'content-length': '167',
              connection: 'close',
              vary: 'Origin',
              'x-request-id': '5ae3d785a0b1293c5b47a72150bae0bc',
              'strict-transport-security': 'max-age=15724800; includeSubDomains',
              'cf-cache-status': 'DYNAMIC',
              server: 'cloudflare',
              'cf-ray': '7d68e57718abf3f9-BOM',
              'alt-svc': 'h3=":443"; ma=86400'
            },
            config: {
              transitional: [Object],
              adapter: [Array],
              transformRequest: [Array],
              transformResponse: [Array],
              timeout: 0,
              xsrfCookieName: 'XSRF-TOKEN',
              xsrfHeaderName: 'X-XSRF-TOKEN',
              maxContentLength: -1,
              maxBodyLength: -1,
              env: [Object],
              validateStatus: [Function: validateStatus],
              headers: [AxiosHeaders],
              method: 'post',
              url: 'https://api.openai.com/v1/completions',
              data: '{"prompt":"hello","max_tokens":60}'
            },
            request: <ref *1> ClientRequest {
              _events: [Object: null prototype],
              _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: '34',
              _hasBody: true,
              _trailer: '',
              finished: true,
              _headerSent: true,
              _closed: false,
              socket: [TLSSocket],
              _header: 'POST /v1/completions HTTP/1.1\r\n' +
                'Accept: application/json, text/plain, */*\r\n' +
                'Content-Type: application/json\r\n' +
                'Authorization: Bearer KEY +
                'User-Agent: axios/1.4.0\r\n' +
                'Content-Length: 34\r\n' +
                'Accept-Encoding: gzip, compress, deflate, br\r\n' +
                'Host: api.openai.com\r\n' +
                'Connection: close\r\n' +
                '\r\n',
              _keepAliveTimeout: 0,
              _onPendingData: [Function: nop],
              agent: [Agent],
              socketPath: undefined,
              method: 'POST',
              maxHeaderSize: undefined,
              insecureHTTPParser: undefined,
              joinDuplicateHeaders: undefined,
              path: '/v1/completions',
              _ended: true,
              res: [IncomingMessage],
              aborted: false,
              timeoutCb: null,
              upgradeOrConnect: false,
              parser: null,
              maxHeadersCount: null,
              reusedSocket: false,
              host: 'api.openai.com',
              protocol: 'https:',
              _redirectable: [Writable],
              [Symbol(kCapture)]: false,
              [Symbol(kBytesWritten)]: 0,
              [Symbol(kNeedDrain)]: false,
              [Symbol(corked)]: 0,
              [Symbol(kOutHeaders)]: [Object: null prototype],
              [Symbol(errored)]: null,
              [Symbol(kUniqueHeaders)]: null
            },
            data: { error: [Object] }
          }
        }

Note: I have replaced the Path & API Key here

I am expecting a response from OpenAI

Front-end code

    <!DOCTYPE HTML>
<html>
<head>
    <title>OpenAI Sample Tool</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h1>OpenAI Chat Example</h1>
    <input type="text" id="inputText" placeholder="Enter your 
text here">
    <button onclick="fetchResponse()">Submit</button>
    <p id="response"></p>

    <script>
        function fetchResponse() {
            var text = $("#inputText").val();
            $.ajax({
                url: 'http://localhost:3000/getOpenAIResponse', 
                type: 'POST',
                data: {input: text},
                success: function(data) {
                    $("#response").html(data);
                }
            });
        }
    </script>
</body>
</html>

Server-side code

                const express = require('express');
            const bodyParser = require('body-parser');
            const axios = require('axios');
            const cors = require('cors');
            const app = express();

            app.use(cors()); // use CORS middleware
            app.use(bodyParser.json());
            app.use(bodyParser.urlencoded({ extended: false }));

            app.post('/getOpenAIResponse', async (req, res) => {
                const prompt = req.body.input;
                try {
                    const response = await 
axios.post('https://api.openai.com/v1/completions', {
                        prompt: prompt,
                        max_tokens: 60,
                        'model': 'text-davinci-003'
                    }, {
                        headers: {
                            'Authorization': 'Bearer KEY'
                        }
                    });
                    
res.send(response.data.choices[0].text.strip());
                } catch (err) {
                    console.error(err);
                    res.send('An error occurred.');
                }
            });

            app.listen(3000, () => console.log('Server running on 
port 3000.'));
Jerome
  • 1
  • 1

0 Answers0