Reputation: 229
With following request payload (generated from JSON.stringify(data)
without error):
{
"model": "gpt-3.5-turbo",
"messages": [
{ "role": "user", "content": "convert 4000 m² into acres." }
]
}
I got following ChatGPT API error response:
invalid_request_error: We could not parse the JSON body of your request.
(HINT: This likely means you aren't using your HTTP library correctly.
The OpenAI API expects a JSON payload, but what was sent was not valid JSON.
If you have trouble figuring out how to fix this, please send an email to [email protected]
and include any relevant code you'd like help with.)
Changing m²
to square meters
solved the problem.
But I couldn't find any restrictions on characters in OpenAI documentation.
So which characters are valid for ChatGPT API, which are not?
For those restricted characters, how to escape/encode them?
Or, should I just filter out those characters?
Edit:
Now I'm pretty sure it's encoding problem. Any non-ascii characters will result in the same error, e.g. some Chinese characters:
{
"model": "gpt-3.5-turbo",
"messages": [{ "role": "user", "content": "一年有多少天" }]
}
Edit 2:
The code is a AWS Lambda function and runtime is Node.js 14.x. The payload looks correct from logs. Here's the code:
const https = require('https');
function apiRequest(data, apiKey) {
let requestBody = JSON.stringify(data);
console.log('payload:', requestBody);
const options = {
hostname: 'api.openai.com',
port: 443,
path: '/v1/chat/completions',
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Accept': 'application/json; charset=utf-8',
'Authorization': `Bearer ${apiKey}`,
'Content-Length': requestBody.length
},
}
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
res.setEncoding('utf-8');
let responseBody = '';
res.on('data', (chunk) => {
responseBody += chunk;
});
res.on('end', () => {
console.log('response:', responseBody);
resolve(JSON.parse(responseBody));
});
});
req.on('error', (err) => {
reject(err);
});
req.write(requestBody, 'utf-8');
req.end();
});
}
Upvotes: 1
Views: 3853
Reputation: 1578
The solution for me was to convert the body to a Buffer before calling req.write
, like so:
let requestBody = JSON.stringify(data);
requestBody= Buffer.from(requestBody , 'utf-8');
req.write(requestBody);
Upvotes: 0
Reputation: 229
Changed runtime to Node.js 18.x and replaced https
with node-fetch
, problem solved.
Upvotes: 0