route.ts 694 B

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