route.ts 550 B

12345678910111213141516171819202122232425
  1. import { OpenAIApi, Configuration } from "openai";
  2. import { ChatRequest } from "./typing";
  3. const apiKey = process.env.OPENAI_API_KEY;
  4. const openai = new OpenAIApi(
  5. new Configuration({
  6. apiKey,
  7. })
  8. );
  9. export async function POST(req: Request) {
  10. try {
  11. const requestBody = (await req.json()) as ChatRequest;
  12. const completion = await openai!.createChatCompletion(
  13. {
  14. ...requestBody,
  15. }
  16. );
  17. return new Response(JSON.stringify(completion.data));
  18. } catch (e) {
  19. return new Response(JSON.stringify(e));
  20. }
  21. }