In the payload, we need to ask in the content to get a response in json
and in the body of the api request we need to add
"response_format": {
"type": "json_object"
}
To be able to use the json format, the content send must include the notion of json.
var request = require('request');
var options = {
'method': 'POST',
'url': 'https://api.openai.com/v1/chat/completions',
'headers': {
'Authorization': 'Bearer sk-YOUR-PRIVATE-KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"model": "gpt-4-1106-preview",
"messages": [
{
"role": "user",
"content": "write a test response in json"
}
],
"response_format": {
"type": "json_object"
}
})
};
request(options, function (error, response) {
if (error) {
throw new Error(error);
}
console.log(response.body);
});
/**
* Response body:
* {
* "id": "chatcmpl-AZERTY123456789",
* "object": "chat.completion",
* "created": 123456789,
* "model": "gpt-4-1106-preview",
* "choices": [
* {
* "index": 0,
* "message": {
* "role": "assistant",
* "content": "{\n \"status\": \"success\",\n \"message\": \"Test response generated successfully\",\n \"data\": {\n \"testId\": 123,\n \"testName\": \"Sample Test\",\n \"duration\": 3600,\n \"questions\": [\n {\n \"questionId\": 1,\n \"type\": \"multiple-choice\",\n \"text\": \"What is the capital of France?\",\n \"options\": [\"Paris\", \"Berlin\", \"London\", \"Madrid\"],\n \"correctAnswer\": \"Paris\"\n },\n {\n \"questionId\": 2,\n \"type\": \"boolean\",\n \"text\": \"The Earth is flat.\",\n \"correctAnswer\": \"False\"\n }\n ]\n },\n \"timestamp\": \"2023-04-01T12:00:00Z\"\n}"
* },
* "finish_reason": "stop"
* }
* ],
* "usage": {
* "prompt_tokens": 13,
* "completion_tokens": 171,
* "total_tokens": 184
* },
* "system_fingerprint": "fp_azerty123"
* }
*/
let jsonMessageContent = json.parse(response.body).choices[0].message.content;
/**
* jsonMessageContent:
*
* {
* "status": "success",
* "message": "Test response generated successfully",
* "data": {
* "testId": 123,
* "testName": "Sample Test",
* "duration": 3600,
* "questions": [
* {
* "questionId": 1,
* "type": "multiple-choice",
* "text": "What is the capital of France?",
* "options": [
* "Paris",
* "Berlin",
* "London",
* "Madrid"
* ],
* "correctAnswer": "Paris"
* },
* {
* "questionId": 2,
* "type": "boolean",
* "text": "The Earth is flat.",
* "correctAnswer": "False"
* }
* ]
* },
* "timestamp": "2023-04-01T12:00:00Z"
* }
*