route.ts 783 B

1234567891011121314151617181920212223242526272829303132333435
  1. import { OpenAIApi, Configuration } from "openai";
  2. import { ChatRequest } from "./typing";
  3. const isProd = process.env.NODE_ENV === "production";
  4. const apiKey = process.env.OPENAI_API_KEY;
  5. const openai = new OpenAIApi(
  6. new Configuration({
  7. apiKey,
  8. })
  9. );
  10. export async function POST(req: Request) {
  11. try {
  12. const requestBody = (await req.json()) as ChatRequest;
  13. const completion = await openai!.createChatCompletion(
  14. {
  15. ...requestBody,
  16. },
  17. isProd
  18. ? {}
  19. : {
  20. proxy: {
  21. protocol: "socks",
  22. host: "127.0.0.1",
  23. port: 7890,
  24. },
  25. }
  26. );
  27. return new Response(JSON.stringify(completion.data));
  28. } catch (e) {
  29. return new Response(JSON.stringify(e));
  30. }
  31. }