route.ts 979 B

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