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

30 lines
694 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:25:33 +00:00
export async function POST(req: Request) {
2023-03-09 17:01:40 +00:00
try {
2023-03-26 11:58:25 +00:00
let apiKey = process.env.OPENAI_API_KEY;
const userApiKey = req.headers.get("token");
if (userApiKey) {
apiKey = userApiKey;
}
const openai = new OpenAIApi(
new Configuration({
apiKey,
})
2023-03-09 17:01:40 +00:00
);
2023-03-26 11:58:25 +00:00
const requestBody = (await req.json()) as ChatRequest;
const completion = await openai!.createChatCompletion({
...requestBody,
});
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));
}
}