I'm building in next.js on replit and attempting to implement an OpenAI integration, but I can't get it to recognize my OpenAI key. I have it correctly added as a secret (replaces .env.local if you're unfamiliar with replit) but I still keep getting this error.
I've tried several different ways to write openai.ts based on suggestions I could find:
sorry for the poor formatting this is my first time here :)
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
});
async function main() {
const chatCompletion = await openai.chat.completions.create({
messages: [{ role: 'user', content: 'Say this is a test' }],
model: 'gpt-3.5-turbo',
});
}
main();
`results in:
Unhandled Runtime Error Error: The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).
Source utils/openai.ts (3:15) @ eval
1 | import OpenAI from 'openai'; 2 |
3 | const openai = new OpenAI({ | ^ 4 | apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted 5 | }); 6 |`
import { OpenAIApi, Configuration } from "openai";
const openAI = new OpenAIApi(new Configuration({
apiKey: process.env.OPENAI_API_KEY,
}));
async function createChatCompletion(prompt) {
const response = await openAI.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [
{
role: "user",
content: prompt,
},
],
});
return response;
}
export { openAI, createChatCompletion };
results in: ` 1 of 1 unhandled error Server Error TypeError: openai__WEBPACK_IMPORTED_MODULE_0__.Configuration is not a constructor
This error happened while generating the page. Any console logs will be displayed in the terminal window. Source utils/openai.ts (3:29) @ eval
1 | import { OpenAIApi, Configuration } from "openai"; 2 |
3 | const openAI = new OpenAIApi(new Configuration({ | ^ 4 | apiKey: process.env.OPENAI_API_KEY, 5 | })); 6 |`
I've stumbled on a similar problem and I've managed to reach OpenAI API.
My code looks like this:
I assume getting the 429 code "exceeded use limit" indicates that I've managed to reach the API.
hope this helps :)