I am trying to call an external API from AWS Lambda but it currently does not provide me anything, no errors or sign of the API request even being sent out. I am frankly not sure what is driving the cause of the issue. I have tried the following.
Change the permissions to allow for HTTP requests
Connected the Lambda Function to a VPC
Below is my code, please let me know if there is anything else I should be looking into.
import fetch from 'node-fetch';
function findWordsInQuotations(sentence) {
// Regular expression to match words within double quotations
// This regex pattern captures words within double quotes
const regex = /"([^"]+)"/g;
// Use the match method to find all words in quotations
const matches = sentence.match(regex);
if (matches) {
// Extract and print the words within quotations
const wordsInQuotations = matches.map(match => match.replace(/"/g, '')); // Remove double quotes
return wordsInQuotations;
} else {
return [];
}
}
async function getReverseDictionary() {
let apiKey = process.env.ChatGPT_API_KEY;
const inputPhrase = "smart but evil";
const inputType = "";
const inputTone = "";
// Use the OpenAI GPT-3 API to find a singular word
let prompt = `What are the five best words for "${inputPhrase}", when you respond, just respond with the words, with the first letter capitalized and all of the words delimited by commas.`;
if (inputType.trim() === "") {
console.log("InputType is empty!");
} else {
prompt = prompt + 'For reference, this is for a ' + inputType;
}
if (inputTone.trim() === "") {
console.log("InputTone is empty!");
} else {
prompt = prompt + '. For reference, I am going for a ' + inputTone + ' tone.';
}
console.log(prompt);
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: "You are a dictionary"
},
{
role: 'user',
content: prompt
}
],
max_tokens: 50, // Limit the response to one token (word)
}),
});
console.log(response);
const data = await response.json();
console.log('the CHATGPT RESPONSE:' + data);
const chatGPToutput = data.choices[0].message.content;
console.log(chatGPToutput);
const singularWord = findWordsInQuotations(chatGPToutput);
const wordsArray = chatGPToutput.split(',');
console.log(wordsArray);
let resultOne = wordsArray[0];
let resultTwo = wordsArray[1];
let resultThree = wordsArray[2];
let resultFour = wordsArray[3];
let resultFive = wordsArray[4];
return resultFive;
}
export const handler = async (event) => {
// TODO implement
;
const response = {
Result_One: getReverseDictionary(),
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
You have to wait till you get back the response from the external API.