OpenAI Fine tuned engine not working in Node - "Engine not found" - node.js

I have fine-tuned an engine on OpenAI using my own data. I can access the engine in the Playground with no issues, however, when I try to access it programmatically using Node & the openai Node library, I get an "Engine not found" error. The weird thing is, I could have sworn it worked before.
Anyway, here is my code:
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
async function getDream() {
const completion = await openai.createCompletion("davinci:ft-personal-2022-04-09-19-12-54", {
prompt: "I dreamed",
});
console.log(completion.data.choices[0].text);
}
getDream();
Here's the error:
error: {
message: 'Engine not found',
type: 'invalid_request_error',
param: null,
code: null
}
I tried running the same code but with a regular engine (davinci). Works fine that way. I've double-checked that I have the name of my fine-tuned engine right and tried it using the engine ID just in case. Nothing seems to work.
PS - I have run this using the OpenAI CLI as well using openai api completions.create -m davinci:ft-personal-2022-04-09-19-12-54 -p "I dreamed" and that works as well.

I'm back, answering my own question in hopes that it will help others.
It seems that if you are using your own fine-tuned model, you have to use a different method than if you use one of the default models. Instead of createCompletion, you should use createCompletionFromModel. So the function above (getDream) should actually look like this:
async function getDream() {
const response = await openai.createCompletionFromModel({
model: 'davinci:ft-personal-2022-04-09-19-12-54',
prompt: 'I dreamed'
// add other parameters here
});
}
You can add other completion parameters to this below prompt, e.g. temperature, frequency_penalty, etc.

Related

Unable to update the custom_attribute field using the node.js intercom-client

I am using the official Intercom node.js 'intercom-client' library (latest version -- 4.0, and node version 16.18) to try to add data to the custom_attribute field for an existing conversation, but keep getting an 'attribute does not exist' error.
According to the Intercom API documentation, it is possible to modify the custom_attribute field of a conversation: https://github.com/intercom/intercom-node#update-a-conversation
https://developers.intercom.com/intercom-api-sreference/reference/update-a-conversation
Using the node.js 'intercom-client' library to interact with the API in javascript, I attempted the following:
Passing the following object: { test: 'hope' }; to the client.conversations.update() method using the following code:
const customAttributes = { test: 'hope' };
client.conversations.update({
id: '68',
customAttributes,
});
I get the following error:
errors: [
{
code: 'parameter_invalid',
message: "Conversation attribute 'test' does not exist"
}
]
I would have expected it to modify the conversation object successfully.
Per the official documentation on the git-hub repo, the following should work:
const response = await client.conversations.update({
id,
markRead: true,
customAttributes: {
anything: 'you want',
},
});
but I get the same error, when I use this code exactly as it is written. I have tried to use snake case for the 'customAttributes' field, i.e. tried 'custom_attributes' without success. I have also tried to pass this object to the conversation at time it is created (using client.conversation.create()), given that the error is suggesting that the object should have been passed earlier, but without success (nothing happens...).
Thank you for your help!
Dan

OpenAI API giving error: 429 Too Many Requests

I am trying to make a request to the openai API with the following code in express nodeJS:
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
organization: "org-Fn2EqsTpiUCTKb8m61wr6H8m",
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
});
const openai = new OpenAIApi(configuration);
async function callApi() {
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: "Say this is a test",
max_tokens: 3000,
temperature: 0,
});
console.log(response.data.choices[0].text);
}
callApi();
The problem is that I keep getting error 429 Too many requests.
Here some more information:
The API key is correct.
When I go to my openai account > view API KEY: it shows that the key was never used so I have never been able to make a call. So how is it possibile that I'm getting error Too many requests?
I have already tried to implement exponential backoff in the function, but it didn't work.
The answer is in the error that you have received.
The error 429 Too Many Requests means that you have exceeded your free $18 in API credits. You can pay for more on the official website.
It's not possible that your key is correct but is not being used when you try to make a request. Double check that you are using the correct key in your code.

Mailchimp and Node.js with typescript noob question: Import vs Require

I am creating an app that sends certain transactional emails using Mailchimp.
They have great docs here: https://mailchimp.com/developer/api/transactional/messages/send-using-message-template/
But Im using typescript, so the line:
var mailchimp = require("mailchimp_transactional")("API_KEY");
Doesn't work, I get the following error:
Error: Cannot find module 'mailchimp_transactional'
I know this is something small, but I am not sure how to get around it at all. I found an article that describes creating your own types file here: #mailchimp/mailchimp_marketing/types.d.ts' is not a module in nodeJs
But there has to be a quicker simpler solution. It also doesn't make it clear how to set the API key in that case.
I have tried to import the module which is #mailchimp/mailchimp_transactional which did not work.
I have ofcourse also run npm install #mailchimp/mailchimp_transactional
Any help would be appreciated, here is a full sample just incase it helps.
var mailchimp = require("mailchimp_transactional")("API_KEY");
export const testSendEmailFromTemplate = async () => {
let mcbody = {
template_name: "my-template",
template_content: [{
name:"firstname",
content:"INJECTED.BY.TEMPLATE.CONT.firstname"
},
{
name:"surname",
content:"INJECTED.BY.TEMPLATE.CONT.surname"
}],
message: {
to:{
email:"email#gmail.com",
name: "Test",
type: "to"
}
},
async:true
};
return await mailchimp.messages.sendTemplate(mcbody);
}
If anyone is unfortunate enough to face this issue because Mailchip's docs don't cater to the typescript setup, and you aren't sure how to make it 'just work' here is the answer:
const mailchimpFactory = require("#mailchimp/mailchimp_transactional/src/index.js");
const mailchimp = mailchimpFactory("PUTKEYHERE");
This pulls in the javascript file directly and then the second line initialises the object.
Good luck all!
As of March 2022 the types have been added to DefinitelyTyped and can be accessed by running
npm install --save-dev #types/mailchimp__mailchimp_transactional
I had the same problem in a node/Typescript project, but this is working for me:
const mailchimp = require('#mailchimp/mailchimp_marketing')
export class MailchimpServices {
constructor() {
mailchimp.setConfig({
apiKey: '...',
server: 'us5',
});
}
async ping() {
console.log('Start mailchimp ping!')
const response = await mailchimp.ping.get();
console.log(response);
}
}

'FIRESTORE INTERNAL ASSERTION FAILED: Unexpected state' when unit testing with Jest

I'ḿ setting up a jest test suite for a Node.js and Express REST API i'm building, i'm using #firebase/testing module to initialize a testing app, however when i try to perform any sort of operation to the database this error comes out:
FIRESTORE (7.17.2) INTERNAL ASSERTION FAILED: Unexpected state
at fail (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/util/assert.ts:39:9)
at hardAssert (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/util/assert.ts:53:5)
at fromBytes (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/remote/serializer.ts:270:5)
at fromWatchChange (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/remote/serializer.ts:486:25)
at PersistentListenStream.onMessage (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/remote/persistent_stream.ts:576:25)
at /home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/remote/persistent_stream.ts:456:21
at /home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/remote/persistent_stream.ts:509:18
at /home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/util/async_queue.ts:369:14
I also tried connecting to my regular firestore database with the credentials i have been using to develop the endpoints and same error pops out even tho it's the app i use daily
Weird thing is, data is being written to the database, but error still stops testing
Here is firebase setup:
(src/db/functions.js)
let app = initializeTestApp({
projectId: "illicit"
})
db = app.firestore()
module.exports = { db }
Function throwing the error
(tests/fixtures/db.js)
const { db } = require('../../src/db/functions')
const bcrypt = require('bcrypt');
const createAdmin = async function() {
// Encrypt password
let encPass = await bcrypt.hash("admin", 8)
let admin = {
name: "Admin Test User",
email: "admin#test.com",
password: encPass,
tokens: []
}
// Add to db
let docRef = await db.collection('admins').add(admin) // <- This line throws the error
return;
}
module.exports = {
createAdmin
}
And finally testing file
(tests/glasses.test.js)
const supertest = require('supertest');
const app = require('../src/app')
const functions = require('./fixtures/db')
let adminToken;
let glassesId;
//Executes before any test, here is where error occurs, before any tests
beforeAll( async () => {
await functions.createAdmin()
return
})
test('Should log in an admin', async () => {
let response = await supertest(app)
.post('/admins/login')
.send({
email: 'admin#test.com',
password: 'admin'
})
.expect(200);
expect(response.body.token).toEqual(expect.any(String))
adminToken = response.token;
});
This only happens only when i try to test, regular app works just fine
Things i've tried:
Firestore rules are read and write true, so it's not a rules error
Mocked Firestore with firebase-mock and Jest seems to work fine, however this is not a
solution, since i need to test data inside the database
Hope you can help me :)
You should change Jest's test environment from the default jsdom to node using jest --env=node or by setting the testEnvironment option to node in your Jest config.
Solved the problem myself, i was using the Firebase web client, I switched to the Admin SDK made specifically for servers, i guess it was some sort of auth problem, because the admin sdk automatically authenticates you in the db
This is a open issue on GitHub. I'm pasting my comment from that issue here to hopefully help some other people:
I experienced the same error message on 9.6.6 with NextJS. I believe
this error message could be presented due to a range of errors - as I
see 100+ Stackoverflow questions with this error message.
After lots of debugging I realized I accidently used SQL
capitalization:
.orderBy('time', 'ASC') = "INTERNAL ASSERTION FAILED: Unexpected state" .orderBy('time', 'asc') = No Errors!
This was a pain to debug, and my mistake was so small. Maybe better
error reporting is needed in cases like this? When you get then Google
this error message it easily leads you down a path of debugging things
completely irrelevant to the real error.
So pretty much - a tiny syntax error can cause the error message and lead you down a road of debugging the wrong things. To solve this you have to find exactly where it is happening and narrow in your debuging.
execute this command with what is indicated a little above yarn test jest --env=node
after this the error disappears

Error snap.data is not a function with firebase cloud function and onCreate

I have a cloud function that sends a welcome email every time a new user registers in the database.
The function correctly executes everything, sends the emails and these are received by the recipient, so far, everything is fine.
It works when I manually write the email address in the function, but when I want it to get the data from the realtime database, it gives me the error:
TypeError: snap.data is not a function
This is the code of my function:
const functions = require('firebase-functions');
const nodemailer = require("nodemailer");
const transport = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "MY_EMAIL",
pass: "MY_EMAIL_PASSWORD"
}
})
exports.welcomeMail = functions.database.ref('/paso1/{id}').onCreate((snap, context) => {
const _name = snap.data().name;
return sendWelcomeMail(_name)
});
// aux functions
function sendWelcomeMail(name) {
return transport.sendMail({
from: "JohnDoe <sender#test.com>",
to: "myfriendemail#gmail.com",
subject: "Hello",
html: `
<h1<Hello ${name} </h1>
<p>nice to seeyou</p>
`
})
.then(r => r)
.catch(e => e);
}
This is my realtime database:
I have reviewed the documentation several times, I have tested with snap.val().{uid}; but all without success, I cannot recover the "name" field from the database.
Using const _name = snap.val().name; I get the same error
I am not sure what is failing.
The method you're looking for is snap.val(), not snap.data(). You might be confusing Realtime Database with Firestore. Firestore uses data() to get the raw data out of a DocumentSnapshot, but that's different than Realtime Database.
You have a typo. You declare snap and then refer to it as snapshot. To fix this problem, make sure the declaration and use match.
You're also using snapshot.data(), while data() doesn't exist on a Realtime Database snapshot (you're probably confusing it with Cloud Firestore).
So combining those two fixes, this should be much closer:
exports.welcomeMail = functions.database.ref('/paso1/{id}')
.onCreate((snapshot, context) => { // this line changed
const _name = snapshot.val().name;
...
I finally found what the mistake was.
Indeed, as you have indicated to me, the correct way to extract the data from the realtime database is by using .val()
However, I told you in the comments to the answers that I kept returning error.
It didn't work because I wasn't initializing the firebase SDK as an ADMIN, necessary to access, among other things, the realtime database.
https://firebase.google.com/docs/admin/setup
I hope my mistake will save other programmers time.
Thanks to all for the help

Resources