I'm trying to simply print an answer in terminal to the "say hello" prompt, but it logs Error: Request failed with status code 400
to the terminal.
Here's the code that tries to use the ChatGPT API:
const axios = require('axios');
async function getChatGptResponse(prompt, apiKey, apiEndpoint) {
const headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
};
const data = {
'messages': [{'role': 'user', 'content': prompt}],
};
try {
const response = await axios.post(apiEndpoint, data, { headers });
return response.data.choices[0].message.content;
} catch (error) {
console.error('Error:', error.message);
return null;
}
}
async function main() {
const apiKey = 'myKey'; // Replace this with your actual API key
const apiEndpoint = 'https://api.openai.com/v1/chat/completions';
const prompt = "say hello";
const response = await getChatGptResponse(prompt, apiKey, apiEndpoint);
if (response) {
console.log('ChatGPT:', response);
}
}
main();