Not getting proper response from GPT-3 using SDK in JS - openai-api

When using createCompletion I get a response but it doesn't have the actual text response. In textPayload it has "text: 'package com.example.demo.controller;',"
Below is my code
const openai = new OpenAIApi(configuration);
async function step1() {
currentResponse = await openai.createCompletion({
model: "text-davinci-003",
prompt: currentMessage,
temperature: 0,
max_tokens: 2292,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
stop: ["\n\n"],
});
} //end step1
return step1().then(function(response) {
var currentResponseNew = currentResponse.data
//this is where I get the text payload value
console.log(currentResponseNew)
res.send("done")
})

Based on your code above, when accessing the response data you need to access the choices parameter from the currentResponse object.
Here is how you should fix your code:
const openai = new OpenAIApi(configuration);
async function step1() {
currentResponse = await openai.createCompletion({
model: "text-davinci-003",
prompt: currentMessage,
temperature: 0,
max_tokens: 2292,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
stop: ["\n\n"],
});
} //end step1
return step1().then(function(response) {
//this is where I get the text payload value
console.log(currentResponse.data.choices[0].text)
res.send("done")
})
When I run this code I get a valid response from GPT.

Related

Fetch count cloudwatch log using node js for a specific date range

Howto get the count ?, i have check the query in cloud watch Insights i got output , can any one help me
async function main(){
const logGroupName = '/aws/apprunner/<Name of your Log Group>';
const timestamp = new Date();
let queryCount = `stats count() as total`;
const params = {
startTime: '1675103400000',
endTime: '1675189799000',
queryString: queryCount,
logGroupName: logGroupName
};
// 1. Start the query. When we start a query, this returns a queryId for us to use on our next step.
const data = await cloudWatchLogs.startQuery(params).promise();
const { queryId } = data;
console.debug('query id', queryId);
// 2. Send Insight query to CloudwatchLogs
const insightData = await cloudWatchLogs.getQueryResults({ queryId })
.promise();
console.log(insightData);
return ;
}
main();
o/p: {
results: [],
statistics: { recordsMatched: 0, recordsScanned: 0, bytesScanned: 0 },
status: 'Running'
}
try to get the count from result from above code i have posted

[InteractionAlreadyReplied]: The reply to this interaction has already been sent or deferred

It says [InteractionAlreadyReplied]: The reply to this interaction has already been sent or deferred. But inreality i am using editReply
I am having issue in logging error, it works fine with try and else but it shows [InteractionAlreadyReplied]: The reply to this interaction has already been sent or deferred in catch (error). I even tried using followUp but still doesnt work, it keeps giving the same error and shuts the whole bot down.
module.exports = {
data: new SlashCommandBuilder()
.setName("chat-gpt")
.setDescription("chat-gpt-3")
.addStringOption(option =>
option.setName('prompt')
.setDescription('Ask Anything')
.setRequired(true)),
async execute(interaction, client) {
const prompt = interaction.options.getString('prompt');
await interaction.deferReply();
const configuration = new Configuration({
apiKey: "nvm",
});
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
model: 'text-davinci-003',
prompt: prompt,
max_tokens: 2048,
temperature: 0.7,
top_p: 1,
frequency_penalty: 0.0,
presence_penalty: 0.0,
});
let responseMessage = response.data.choices[0].text;
/* Exceed 2000 */
try {
let responseMessage = response.data.choices[0].text;
if (responseMessage.length >= 2000) {
const attachment = new AttachmentBuilder(Buffer.from(responseMessage, 'utf-8'), { name: 'chatgpt-response.txt' });
const limitexceed = new EmbedBuilder()
.setTitle(`Reached 2000 characters`)
.setDescription(`Sorry, but you have already reached the limit of 2000 characters`)
.setColor(`#FF6961`);
await interaction.editReply({ embeds: [limitexceed], files: [attachment] });
} else {
const responded = new EmbedBuilder()
.setTitle(`You said: ${prompt}`)
.setDescription(`\`\`\`${response.data.choices[0].text}\`\`\``)
.setColor(`#77DD77`);
await interaction.editReply({ embeds: [responded] });
}
} catch (error) {
console.error(error);
await interaction.followUp({ content: `error` });
}
return;
},
};
i even tried using followUp or etc but the result is still same.
Your Problem
I believe the error occur in the catch() method (Line 55).
Please be reminded that the interaction has been deferred at Line 14:
await interaction.deferReply();
Explanation
Each interaction can only be replied and deferred once only. If you want to make changes on it, consider using the editReply() method.
Solution
Simply replace the code on Line 55 with editReply and this will solve the current error.
await interaction.editReply({ content: `error` });

HTTP POST request test is not getting passed

I wrote some nodejs codes to be evaluated by a particular test file, candidate.test.js but surprisingly the test keeps failing. Below is the error I am getting:
Error: expect(received).toEqual(expected) // deep equality
Expected: 201
Received: 500
I have below the snippet from both app.js and candidate.test.js.
candidate.test.js
const request = require('supertest');
const app = require('../app');
// ...
async function makeRegularGetRequest(requestBody) {
return await request(app)
.post('/restaurant')
.send(requestBody)
.expect('Content-Type', /json/);
}
it('should create a restaurant given valid parameters', async () => {
const requestBody = {
name: '123',
position: 200,
category: 'Pizza',
rating: 5,
};
const createResponse = await makeRegularPostRequest(requestBody);
try {
expect(createResponse.status).toEqual(201);
} catch (error) {
throw error;
}
});
// ...
app.js
// ...
app.post('/restaurant', (request, response) => {
const id = generateRandomString();
const { name, position, category, rating } = request.body;
const restaurant = {
name: name,
position: position,
category: category,
rating: Number(rating),
id: id,
};
restaurants.push(restaurant);
response.send(restaurant).status(201);
});
// ...
I also tried sending only the statusCode to the page using reponse.send(restaurant).status(201).statusCode, but the error still comes out.
I tested this on Postman and it works really fine but it's strange that the test does not pass.
can you console log before and after pushing to restaurants array

Async Await issues with NodeJS & AWS Lambda

I'm currently developing a Lamba function call for my AWS project, but with me not being a master at asynchronous functions it appears it's falling apart, the code I've put together is:
const AWS = require("aws-sdk");
const game = require('game-api');
const uuid = require("uuid");
AWS.config.update({
region: "us-east-1"
});
exports.handler = async (event, context, callback) => {
//set db
var documentClient = new AWS.DynamoDB.DocumentClient()
//params
const params = {
Item: {
'id': uuid.v1(),
'player_1_name': null,
'player_1_network': null,
'player_1_matches': 0,
'player_1_kills': 0,
'player_1_last_updated': 0,
'player_2_name': null,
'player_2_network': null,
'player_2_matches': 0,
'player_2_kills': 0,
'player_2_last_updated': 0,
'match_id': 0,
'status': 0
},
TableName : 'matches'
};
var matchData = JSON.parse(event.body);
//player 1
const player_1_name = matchData.player_1_name ? matchData.player_1_name : null;
const player_1_network = matchData.player_1_network ? matchData.player_1_network : null;
//player 2
const player_2_name = matchData.player_2_name ? matchData.player_2_name : null;
const player_2_network = matchData.player_2_network ? matchData.player_2_network : null;
//match data
const match_id = matchData.match_id ? matchData.match_id : 0;
//game object
let gameAPI = new game(
[
"email#email.com",
"password"
]
);
//gameAPI.login() returns a Promise()
await gameAPI.login().then(() => {
//check stats for player 1, getStats returns a Promise()
gameAPI.getStats(player_1_name, player_1_network).then(stats => {
params.Item.player_1_matches = stats.lifetimeStats.matches;
params.Item.player_1_kills = stats.lifetimeStats.kills;
}).catch(err => {
//error! we must work out what to do here!
console.log(err);
});
//example insert
documentClient.put(params, function(err, data){
return callback(err, data);
});
}).catch(err => {
console.log("We failed to login!");
console.log(err);
});
};
This logic seems flawed since nothing is being thrown to my AWS logs? my idea is to send the request to the function & have it do it as quickly as possible so I can send a 200 response back to Lambda, can anyone point me in the correct direction?
When using async/await you don't need to use callback neither you need to fall into the Promise Hell.
Just await on your promises and grab the result. The great advantage here is it looks as though your code is synchronous.
Here's your refactored code:
const AWS = require("aws-sdk");
const game = require('game-api');
const uuid = require("uuid");
AWS.config.update({
region: "us-east-1"
});
exports.handler = async (event) => {
//set db
var documentClient = new AWS.DynamoDB.DocumentClient()
//params
const params = {
Item: {
'id': uuid.v1(),
'player_1_name': null,
'player_1_network': null,
'player_1_matches': 0,
'player_1_kills': 0,
'player_1_last_updated': 0,
'player_2_name': null,
'player_2_network': null,
'player_2_matches': 0,
'player_2_kills': 0,
'player_2_last_updated': 0,
'match_id': 0,
'status': 0
},
TableName : 'matches'
};
var matchData = JSON.parse(event.body);
//player 1
const player_1_name = matchData.player_1_name ? matchData.player_1_name : null;
const player_1_network = matchData.player_1_network ? matchData.player_1_network : null;
//player 2
const player_2_name = matchData.player_2_name ? matchData.player_2_name : null;
const player_2_network = matchData.player_2_network ? matchData.player_2_network : null;
//match data
const match_id = matchData.match_id ? matchData.match_id : 0;
//game object
let gameAPI = new game(
[
"email#email.com",
"password"
]
);
//gameAPI.login() returns a Promise()
await gameAPI.login()
const stats = await gameAPI.getStats(player_1_name, player_1_network)
params.Item.player_1_matches = stats.lifetimeStats.matches;
params.Item.player_1_kills = stats.lifetimeStats.kills;
//example insert
await documentClient.put(params).promise();
};
If you need to handle the exceptions (you should) just wrap your await calls in try/catch blocks, like this:
try {
console.log(await somePromise)
} catch (e) {
console.log(e)
}
The snippet above is equivalent to:
somePromise.then(console.log).catch(console.log)
with the great difference that you don't need to chain promises/asynchronous code in order to keep the execution order, so I highly recommend you pick the async/await approach and forget about .then().catch()

Using promises with PDFMake on Firebase Cloud Functions

I am using PDFMake (a variant of PDFKit) to generate PDFs on Firebase Cloud Functions using a realtime database trigger. The function gets all relevant data from the database and then passes it to the function that is supposed to generate the PDF.
All this is done using Promises. Everything works fine until the point where the PDF is actually generated.
Here's the code in my main event listener:
exports.handler = (admin, event, storage) => {
const quotationData = event.data.val();
// We must return a Promise when performing async tasks inside Functions
// Eg: Writing to realtime db
const companyId = event.params.companyId;
settings.getCompanyProfile(admin, companyId)
.then((profile) => {
return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
})
.then(() => {
console.log('Generation Successful. Pass for email');
})
.catch((err) => {
console.log(`Error: ${err}`);
});
};
To generate the PDF, here's my code:
exports.generatePDF = (fonts, companyInfo, quotationData, storage) => {
const printer = new PdfPrinter(fonts);
const docDefinition = {
content: [
{
text: [
{
text: `${companyInfo.title}\n`,
style: 'companyHeader',
},
`${companyInfo.addr_line1}, ${companyInfo.addr_line2}\n`,
`${companyInfo.city} (${companyInfo.state}) - INDIA\n`,
`Email: ${companyInfo.email} • Web: ${companyInfo.website}\n`,
`Phone: ${companyInfo.phone}\n`,
`GSTIN: ${companyInfo.gst_registration_number} • PAN: AARFK6552G\n`,
],
style: 'body',
//absolutePosition: {x: 20, y: 45}
},
],
styles: {
companyHeader: {
fontSize: 18,
bold: true,
},
body: {
fontSize: 10,
},
},
pageMargins: 20,
};
return new Promise((resolve, reject) => {
// const bucket = storage.bucket(`${PROJECT_ID}.appspot.com`);
// const filename = `${Date.now()}-quotation.pdf`;
// const file = bucket.file(filename);
// const stream = file.createWriteStream({ resumable: false });
const pdfDoc = printer.createPdfKitDocument(docDefinition);
// pdfDoc.pipe(stream);
const chunks = [];
let result = null;
pdfDoc.on('data', (chunk) => {
chunks.push(chunk);
});
pdfDoc.on('error', (err) => {
reject(err);
});
pdfDoc.on('end', () => {
result = Buffer.concat(chunks);
resolve(result);
});
pdfDoc.end();
});
};
What could be wrong here that is preventing the promise and thereby the quotation code to be executed as intended?
On firebase log, all I see is Function execution took 3288 ms, finished with status: 'ok'
Based on the execution time and lack of errors, it looks like you're successfully creating the buffer for the PDF but you're not actually returning it from the function.
.then((profile) => {
return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
})
.then(() => {
console.log('Generation Successful. Pass for email');
})
In the code above, you're passing the result to the next then block, but then returning undefined from that block. The end result of this Promise chain will be undefined. To pass the result through, you'd want to return it at the end of the Promise chain:
.then((profile) => {
return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
})
.then(buffer => {
console.log('Generation Successful. Pass for email');
return buffer;
})
I'm trying to experiment generating pdf using firebase cloud function but I am blocked about defining fonts parameter.
Here's my definition:
var fonts = {
Roboto: {
normal: './fonts/Roboto-Regular.ttf',
bold: './fonts/Roboto-Bold.ttf',
italics: './fonts/Roboto-Italic.ttf',
bolditalics: './fonts/Roboto-BoldItalic.ttf'
}
};
I've created a fonts folder which contain the for above files. However wherever I set the fonts folder (in root, in functions folder or in node_modules folder), I get the error 'no such file or directory' when deploying functions. Any advice would be very much appreciated.

Resources