@reliverse/rse
Version:
@reliverse/rse is your all-in-one companion for bootstrapping and improving any kind of projects (especially web apps built with frameworks like Next.js) — whether you're kicking off something new or upgrading an existing app. It is also a little AI-power
71 lines (70 loc) • 2.12 kB
JavaScript
import { relinka } from "@reliverse/relinka";
import { inputPrompt } from "@reliverse/rempts";
import dotenv from "dotenv";
import { ofetch } from "ofetch";
import { updateReliverseMemory } from "../../utils/reliverseMemory.js";
dotenv.config();
export async function ensureOpenAIKey(memory) {
let envKeyInvalid = false;
let memoryKeyInvalid = false;
if (process.env.OPENAI_API_KEY) {
try {
await ofetch("https://api.openai.com/v1/models", {
headers: {
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`
}
});
return process.env.OPENAI_API_KEY;
} catch {
envKeyInvalid = true;
relinka(
"warn",
"OpenAI key in .env file is invalid, let me check my memory..."
);
}
}
if (memory.openaiKey) {
try {
await ofetch("https://api.openai.com/v1/models", {
headers: { Authorization: `Bearer ${memory.openaiKey}` }
});
process.env.OPENAI_API_KEY = memory.openaiKey;
if (envKeyInvalid) {
relinka(
"info",
"Found valid key in memory, using it instead of invalid .env key"
);
}
return memory.openaiKey;
} catch {
memoryKeyInvalid = true;
relinka("warn", "OpenAI key in memory is invalid");
}
}
if (envKeyInvalid || memoryKeyInvalid) {
relinka(
"info",
"Please provide a new OpenAI API key as existing ones are invalid"
);
}
const token = await inputPrompt({
title: "Please enter your OpenAI API key.\n(It will be securely stored on your machine):",
content: "Get one at https://platform.openai.com/api-keys",
validate: async (value) => {
if (!value?.trim()) {
return "API key is required";
}
try {
await ofetch("https://api.openai.com/v1/models", {
headers: { Authorization: `Bearer ${value}` }
});
return true;
} catch {
return "Invalid API key. Please check your key and try again.";
}
}
});
await updateReliverseMemory({ openaiKey: token });
process.env.OPENAI_API_KEY = token;
return token;
}