Reputation: 1
I am trying to use OpenAI's API. My code works great when I tested my API key directly in my code, but when I tried moving it to a .env file, it stopped working. I've been trying to figure out what the issue is but cannot figure it out.
Here is my code:
import OpenAI from "openai";
const apiKey: string = process.env.OPENAI_API_KEY;
const assistantId: string = process.env.OPENAI_ASSISTANT_ID;
console.log(apiKey)
console.log(assistantId)
// Check if API key is provided
if (!apiKey) {
console.error("The OPENAI_API_KEY environment variable is missing or empty.");
}
const openai = new OpenAI({ apiKey: apiKey });
Here is the error I have been receiving: 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' }).
But when I console.log my apiKey, I see it in my server console.
I am using Next.js, and have read that Next has built in .env support so I don't need to npm install dotenv. I've tried using .env.local instead of standard .env and still having issues.
I'm also worried that my helper function is being client side rendered which is why my API key could be coming back as undefined.
I don't want my API key to be displayed publically with NEXT_PUBLIC_.
Is there another way to get this working?
Any ideas on what I could be missing?
Upvotes: 0
Views: 848
Reputation: 79
in your .env or .env.local add
NEXT_PUBLIC_OPENAI_API_KEY="you-key"
and then you can make a server component like (serverai.tsx):
import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
export const runOpenAI = async () => {
const openai = createOpenAI({ apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY })
const { text } = await generateText({
model: openai('gpt-3.5-turbo'),
system: 'You are a friendly assistant!',
prompt: 'Why is the sky blue?',
});
console.log(text);
}
finally, call from a client component:
'use client'
import { runOpenAI } from './serverai';
export default function Home() {
return (
<div>
<button onClick={() => runOpenAI()}>Run OpenAI</button>
</div>
);
}
Upvotes: -1