feat: support using user api key

This commit is contained in:
Yifei Zhang
2023-03-26 11:58:25 +00:00
parent 1e89fe14ac
commit df66eef919
7 changed files with 58 additions and 19 deletions

View File

@@ -1,23 +1,26 @@
import { OpenAIApi, Configuration } from "openai";
import { ChatRequest } from "./typing";
const apiKey = process.env.OPENAI_API_KEY;
const openai = new OpenAIApi(
new Configuration({
apiKey,
})
);
export async function POST(req: Request) {
try {
const requestBody = (await req.json()) as ChatRequest;
const completion = await openai!.createChatCompletion(
{
...requestBody,
}
let apiKey = process.env.OPENAI_API_KEY;
const userApiKey = req.headers.get("token");
if (userApiKey) {
apiKey = userApiKey;
}
const openai = new OpenAIApi(
new Configuration({
apiKey,
})
);
const requestBody = (await req.json()) as ChatRequest;
const completion = await openai!.createChatCompletion({
...requestBody,
});
return new Response(JSON.stringify(completion.data));
} catch (e) {
console.error("[Chat] ", e);