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

27 lines
583 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-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-15 17:24:03 +00:00
}
2023-03-09 17:01:40 +00:00
);
return new Response(JSON.stringify(completion.data));
} catch (e) {
2023-03-19 14:13:00 +00:00
console.error("[Chat] ", e);
2023-03-09 17:01:40 +00:00
return new Response(JSON.stringify(e));
}
}