ChatGPT-Next-Web/app/api/chat/route.ts

48 lines
979 B
TypeScript
Raw Normal View History

2023-03-09 17:01:40 +00:00
import { OpenAIApi, Configuration } from "openai";
2023-03-10 18:25:33 +00:00
import { ChatRequest } from "./typing";
2023-03-09 17:01:40 +00:00
2023-03-10 18:47:29 +00:00
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,
})
);
}
2023-03-09 17:01:40 +00:00
2023-03-10 18:25:33 +00:00
export async function POST(req: Request) {
2023-03-10 18:47:29 +00:00
if (!openai) {
await initService();
}
2023-03-09 17:01:40 +00:00
try {
2023-03-10 18:25:33 +00:00
const requestBody = (await req.json()) as ChatRequest;
2023-03-10 18:47:29 +00:00
const completion = await openai!.createChatCompletion(
2023-03-09 17:01:40 +00:00
{
2023-03-10 18:25:33 +00:00
...requestBody,
2023-03-09 17:01:40 +00:00
},
2023-03-10 18:47:29 +00:00
isProd
? {}
: {
proxy: {
protocol: "socks",
host: "127.0.0.1",
port: 7890,
},
}
2023-03-09 17:01:40 +00:00
);
return new Response(JSON.stringify(completion.data));
} catch (e) {
return new Response(JSON.stringify(e));
}
}