From 144eb684143db99abb0cbe12263369844f76cb9d Mon Sep 17 00:00:00 2001 From: Yidadaa Date: Sat, 11 Mar 2023 02:47:29 +0800 Subject: [PATCH] feat: prod/dev env settings --- app/api/chat/config.template.ts | 1 + app/api/chat/route.ts | 44 ++++++++++++++++++++++----------- yarn.lock | 9 ++++++- 3 files changed, 39 insertions(+), 15 deletions(-) create mode 100644 app/api/chat/config.template.ts diff --git a/app/api/chat/config.template.ts b/app/api/chat/config.template.ts new file mode 100644 index 00000000..1b297a9f --- /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 a6b73c9d..447b36dc 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 b5aef832..51254145 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==