Currently working on a project in next.js through replit and attempting to integrate OpenAI, but struggling with getting it to recognize my API key. The key is correctly added as a secret (similar to .env.local for those unfamiliar with replit), yet I keep encountering this error.
I've experimented with different approaches to writing openai.ts based on various recommendations I could find:
Apologies for the messy formatting, still new here :)
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'], // This is the default setting that can be excluded
});
async function main() {
const chatCompletion = await openai.chat.completions.create({
messages: [{ role: 'user', content: 'Testing' }],
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: 'Your 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 setting that can be excluded 5 | }); 6 |`
import { OpenAIApi, Configuration } from "openai";
// Encounter an issue with Configuration not being a constructor
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 occurred 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 |`