2023-03-29 17:45:26 +00:00
|
|
|
import { NextRequest } from "next/server";
|
|
|
|
|
|
|
|
const OPENAI_URL = "api.openai.com";
|
|
|
|
const DEFAULT_PROTOCOL = "https";
|
|
|
|
const PROTOCOL = process.env.PROTOCOL ?? DEFAULT_PROTOCOL;
|
|
|
|
const BASE_URL = process.env.BASE_URL ?? OPENAI_URL;
|
|
|
|
|
|
|
|
export async function requestOpenai(req: NextRequest) {
|
|
|
|
const apiKey = req.headers.get("token");
|
|
|
|
const openaiPath = req.headers.get("path");
|
|
|
|
|
2023-04-14 18:50:04 +00:00
|
|
|
let baseUrl = BASE_URL;
|
|
|
|
|
|
|
|
if (!baseUrl.startsWith("http")) {
|
|
|
|
baseUrl = `${PROTOCOL}://${baseUrl}`;
|
|
|
|
}
|
|
|
|
|
2023-03-29 17:45:26 +00:00
|
|
|
console.log("[Proxy] ", openaiPath);
|
2023-04-14 18:50:04 +00:00
|
|
|
console.log("[Base Url]", baseUrl);
|
2023-03-29 17:45:26 +00:00
|
|
|
|
2023-04-19 11:28:33 +00:00
|
|
|
if (process.env.OPENAI_ORG_ID) {
|
|
|
|
console.log("[Org ID]", process.env.OPENAI_ORG_ID);
|
|
|
|
}
|
|
|
|
|
2023-04-14 18:50:04 +00:00
|
|
|
return fetch(`${baseUrl}/${openaiPath}`, {
|
2023-03-29 17:45:26 +00:00
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
Authorization: `Bearer ${apiKey}`,
|
2023-05-01 15:48:23 +00:00
|
|
|
...(process.env.OPENAI_ORG_ID && {
|
|
|
|
"OpenAI-Organization": process.env.OPENAI_ORG_ID,
|
|
|
|
}),
|
2023-03-29 17:45:26 +00:00
|
|
|
},
|
2023-05-01 15:48:23 +00:00
|
|
|
cache: "no-store",
|
2023-03-29 17:45:26 +00:00
|
|
|
method: req.method,
|
|
|
|
body: req.body,
|
|
|
|
});
|
|
|
|
}
|