im trying to get chatgpt setup on my lambda server .
having issues getting a response .
here is the server side .
specifically just the async function sendtochatgpt that is setup to receive a user message from my client
// Importing required modules
global.AbortController = require("abort-controller");
const fs = require('fs');
const axios = require('axios');
// Function to send a message to ChatGPT and return the response
async function sendToChatGPT(userMessage) {
try {
const requestData = {
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: userMessage
}
]
};
const config = {
headers: {
'Authorization': `Bearer MY_API`,
'Content-Type': 'application/json'
}
};
const response = await axios.post('https://api.openai.com/v1/engines/gpt-3.5-turbo/completions', requestData, config);
return response.data.choices[0].message.content;
} catch (error) {
console.error('Error sending message to ChatGPT:', error);
return 'An error occurred while communicating with ChatGPT.';
}
}
// Lambda function handler
exports.handler = async (event) => {
const headers = {
'Access-Control-Allow-Origin': 'MYSITE',
'Access-Control-Allow-Headers': 'content-type',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Expose-Headers': 'Access-Control-Max-Age',
'Access-Control-Max-Age': '3600',
'Access-Control-Allow-Credentials': 'false',
};
if (event.httpMethod === 'OPTIONS') {
return {
statusCode: 200,
headers: headers,
body: JSON.stringify({ message: 'CORS headers set successfully' }),
};
}
const userAccessKey = event.body && JSON.parse(event.body).accessKey;
const userMessage = event.body && JSON.parse(event.body).message;
try {
const data = fs.readFileSync('keys.txt', 'utf8');
const validKeys = data.split('\n').map(key => key.trim());
if (!validKeys.includes(userAccessKey)) {
return {
statusCode: 403,
body: JSON.stringify({ valid: false }),
headers: headers,
};
}
const chatGPTResponse = await sendToChatGPT(userMessage);
return {
statusCode: 200,
body: JSON.stringify({ valid: true, chatGPTResponse }),
headers: headers,
};
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify({ error: 'Failed to process the request' }),
headers: headers,
};
}
};