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";
|
2023-03-11 12:54:24 +00:00
|
|
|
const apiKey = process.env.OPENAI_API_KEY;
|
2023-03-10 18:47:29 +00:00
|
|
|
|
2023-03-10 18:53:34 +00:00
|
|
|
const 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-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));
|
|
|
|
}
|
|
|
|
}
|