AxiosError: Request failed with status code 400

im getting the error “OpenAI API Error: AxiosError: Request failed with status code 400” even though my api is working when test in postman for get modules, api key is in working state, even i have tried with multiple api keys? any idea ?

Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.

“OpenAI API Error:” indicates you are using typical exception boilerplate, not whether that was the error message that was returned by an OpenAI server.

Is it you that is using Axios as middleware?

If it is consistent, while a small python example script to get an API response works fine, it would be seemingly your implementation and http network path, or mis-specification of the endpoint or keys in request.

ChatGPT may have helpful debugging advice when given an explanation of your environment, use, and code.

Inspect the full response body and it will have a specific error message on what went wrong.

OpenAI API Error: AxiosError: Request failed with status code 400
at settle (C:\Users\narva\chatbot-chatgpt\node_modules\axios\dist\node\axios.cjs:1909:12)
at IncomingMessage.handleStreamEnd (C:\Users\narva\chatbot-chatgpt\node_modules\axios\dist\node\axios.cjs:2989:11)
at IncomingMessage.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83: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: null },
validateStatus: [Function: validateStatus],
headers: AxiosHeaders {
Accept: ‘application/json, text/plain, /’,
‘Content-Type’: ‘application/json’,
Authorization: ‘Bearer sk-myApiKey’,
‘User-Agent’: ‘axios/1.4.0’,
‘Content-Length’: ‘251’,
‘Accept-Encoding’: ‘gzip, compress, deflate, br’
},
method: ‘post’,
data: ‘{“model”:“gpt-3.5-turbo”,“messages”:[{“role”:“system”,“content”:“You are an assistant specialized in technolog. You only respond to technolog-related questions. For any other question, please ask another assistant.”},{“role”:“user”}],“max_tokens”:100}’
},
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: ‘251’,
_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,
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 10,
connecting: false,
_hadError: false,
_parent: null,
_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)]: 23,
[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],
[Symbol(RequestTimeout)]: undefined
},
_header: ‘POST /v1/chat/completions HTTP/1.1\r\n’ +
‘Accept: application/json, text/plain, /\r\n’ +
‘Content-Type: application/json\r\n’ +
‘Authorization: Bearer sk-myApiKey\r\n’ +
‘User-Agent: axios/1.4.0\r\n’ +
‘Content-Length: 251\r\n’ +
‘Accept-Encoding: gzip, compress, deflate, br\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: ‘:’,
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,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: ,
aborted: false,
upgrade: false,
url: ‘’,
method: null,
statusCode: 400,
statusMessage: ‘Bad Request’,
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [Circular *1],
redirects: ,
[Symbol(kCapture)]: false,
[Symbol(kHeaders)]: [Object],
[Symbol(kHeadersCount)]: 40,
[Symbol(kTrailers)]: null,
[Symbol(kTrailersCount)]: 0,
[Symbol(RequestTimeout)]: undefined
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
protocol: ‘h:’,
_redirectable: Writable {
_writableState: [WritableState],
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: ,
_requestBodyLength: 251,
_requestBodyBuffers: ,
_onNativeResponse: [Function (anonymous)],
_currentRequest: [Circular 1],
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false,
[Symbol(kBytesWritten)]: 0,
[Symbol(kEndCalled)]: true,
[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(kUniqueHeaders)]: null
},
response: {
status: 400,
statusText: ‘Bad Request’,
headers: AxiosHeaders {
date: ‘Sun, 16 Jul 2023 05:35:38 GMT’,
‘content-type’: ‘application/json’,
‘content-length’: ‘160’,
connection: ‘close’,
‘access-control-allow-origin’: '
',
‘openai-organization’: ‘user-9meo7p0li3gf1bhnny3xiutj’,
‘openai-processing-ms’: ‘3’,
‘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’: ‘199’,
‘x-ratelimit-remaining-tokens’: ‘39860’,
‘x-ratelimit-reset-requests’: ‘7m12s’,
‘x-ratelimit-reset-tokens’: ‘210ms’,
‘x-request-id’: ‘ff3c965c0ac8fb83c934ba9155754c1a’,
‘cf-cache-status’: ‘DYNAMIC’,
server: ‘cloudflare’,
‘cf-ray’: ‘7e77e208e88b79ef-HYD’,
‘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’,
data: ‘{“model”:“gpt-3.5-turbo”,“messages”:[{“role”:“system”,“content”:“You are an assistant specialized in technolog. You only respond to technolog-related questions. For any other question, please ask another assistant.”},{“role”:“user”}],“max_tokens”:100}’
},
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: ‘251’,
_hasBody: true,
_trailer: ‘’,
finished: true,
_headerSent: true,
_closed: false,
socket: [TLSSocket],
_header: ‘POST /v1/chat/completions HTTP/1.1\r\n’ +
‘Accept: application/json, text/plain, /\r\n’ +
‘Content-Type: application/json\r\n’ +
‘Authorization: Bearer sk-…apikey\r\n’ +
‘User-Agent: axios/1.4.0\r\n’ +
‘Content-Length: 251\r\n’ +
‘Accept-Encoding: gzip, compress, deflate, br\r\n’ +
‘Connection: close\r\n’ +
‘\r\n’,
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: [Agent],
socketPath: undefined,
method: ‘POST’,
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: ‘/v1/chat/completions’,
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
protocol: ‘hts:’,
_redirectable: [Writable],
[Symbol(kCapture)]: false,
[Symbol(kBytesWritten)]: 0,
[Symbol(kEndCalled)]: true,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype],
[Symbol(kUniqueHeaders)]: null
},
data: { error: [Object] }
}
}

data: ‘{
  “model”:“gpt-3.5-turbo”,
  “messages”:[
    {
      “role”:“system”,
      “content”:“You are an assistant specialized in technolog. You only respond to technolog-related questions. For any other question, please ask another assistant.”
    },
    {
      “role”:“user”
    }
  ],
  “max_tokens”:100
}’

You seem to be missing a content entry for the user role.

If you have no content for that role , it should be "content":"" not just missing

i have content for the user too. here is my code

const systemMessage = You are an assistant specialized in ${categories.join(', ')}. You only respond to ${categories.join(', ')}-related questions. For any other question, please ask another assistant.;

// Construct the messages array with the system message and user question
const messages = [
{ role: ‘system’, content: systemMessage },
{ role: ‘user’, content: question },
];

here is my total code file …

ignore this line
const response = await axios.post(‘httpsr://api.openai.con/v1/chat/completions’, payload, {

******it doest allow links here i have all the spellings correct in my code

const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const axios = require(‘axios’);
const dotenv = require(‘dotenv’);

// Load environment variables from .env file
dotenv.config();

// Initialize express app
const app = express();

// Parse application/json request bodies
app.use(bodyParser.json());

// Create HTTP POST endpoint that accepts user input
// and sends it to OpenAI Chat API
// then returns the response to the client
app.post(‘/api/category/getResponse’, async (req, res) => {
const { categories, question } = req.body;

// Construct the system message based on the provided categories
const systemMessage = You are an assistant specialized in ${categories.join(', ')}. You only respond to ${categories.join(', ')}-related questions. For any other question, please ask another assistant.;

// Construct the messages array with the system message and user question
const messages = [
{ role: ‘system’, content: systemMessage },
{ role: ‘user’, content: question },
];

// Construct the request payload
const payload = {
model: ‘gpt-3.5-turbo’,
messages,
max_tokens: 100,
};

try {
// Send a request to the OpenAI API with the user’s prompt
const response = await axios.post(‘httpsr://api.openai.con/v1/chat/completions’, payload, {
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: Bearer ${process.env.API_KEY},
},
});

if (response.status !== 200) {
  throw new Error('OpenAI API Error');
}

// Get the bot's answer from the OpenAI API response
const botAnswer = response.data.choices[0].message.content;

// Check if the bot's answer is suitable for the question's category
const isSuitable = categories.some(category => botAnswer.includes(category));

// If the answer is suitable, send it back to the client
// Otherwise, send an appropriate message
const responseData = isSuitable ? botAnswer : "I'm not suitable for this task.";

// Send the response back to the client
return res.json({ status: 'success', data: responseData });

} catch (error) {
console.error(‘OpenAI API Error:’, error);
if (error.response) {
// The request was made and the server responded with a status code
console.log(‘Response data:’, error.response.data);
console.log(‘Response status:’, error.response.status);
console.log(‘Response headers:’, error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log(‘Request:’, error.request);
} else {
// An error occurred during the request setup
console.log(‘Error message:’, error.message);
}
console.log(‘Error config:’, error.config);
return res.json({ status: ‘error’, data: null });
}
});

// Set the port to listen on
// which is either the port specified in the .env
// or 3000 if no port is specified
const PORT = process.env.PORT || 3000;

// Start the express server
app.listen(PORT, () => console.log(Server listening on localhost:${PORT}));

All I can tell you is that the log file you have there is missing the user role contents, where is this library from?

the code is working fine as of now thanks for the support bro.

1 Like

Hi,I am facing the same problem as you, may I ask how to fix it?

Look at the full response you’ll get a more descriptive error message. Wrap your code in a try catch like this and get the message to share here if you still need help resolving the issue.

try {
    const response = await openai.createChatCompletion({
        <.......>
} catch (error) {
    console.error(error.response.data ?? error.message);
}
1 Like