diff --git a/app/api/chat/config.template.ts b/app/api/chat/config.template.ts new file mode 100644 index 000000000..1b297a9fc --- /dev/null +++ b/app/api/chat/config.template.ts @@ -0,0 +1 @@ +export const apiKey = "your dev api key here"; diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts index a6b73c9d6..447b36dc6 100644 --- a/app/api/chat/route.ts +++ b/app/api/chat/route.ts @@ -1,27 +1,43 @@ import { OpenAIApi, Configuration } from "openai"; -import { apiKey } from "./config"; import { ChatRequest } from "./typing"; -// set up openai api client -const config = new Configuration({ - apiKey, -}); -const openai = new OpenAIApi(config); +const isProd = process.env.NODE_ENV === "production"; + +let openai: OpenAIApi | undefined; +async function initService() { + let apiKey = process.env.OPENAI_API_KEY; + + if (!isProd) { + apiKey = await (await import("./config")).apiKey; + } + + openai = new OpenAIApi( + new Configuration({ + apiKey, + }) + ); +} export async function POST(req: Request) { + if (!openai) { + await initService(); + } + try { const requestBody = (await req.json()) as ChatRequest; - const completion = await openai.createChatCompletion( + const completion = await openai!.createChatCompletion( { ...requestBody, }, - { - proxy: { - protocol: "socks", - host: "127.0.0.1", - port: 7890, - }, - } + isProd + ? {} + : { + proxy: { + protocol: "socks", + host: "127.0.0.1", + port: 7890, + }, + } ); return new Response(JSON.stringify(completion.data)); diff --git a/yarn.lock b/yarn.lock index b5aef8328..512541458 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1742,7 +1742,14 @@ cosmiconfig@^7.0.1: path-type "^4.0.0" yaml "^1.10.0" -cross-spawn@^7.0.2, cross-spawn@^7.0.3: +cross-env@^7.0.3: + version "7.0.3" + resolved "https://registry.npmmirror.com/cross-env/-/cross-env-7.0.3.tgz#865264b29677dc015ba8418918965dd232fc54cf" + integrity sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw== + dependencies: + cross-spawn "^7.0.1" + +cross-spawn@^7.0.1, cross-spawn@^7.0.2, cross-spawn@^7.0.3: version "7.0.3" resolved "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==