-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
openai-handler.ts
45 lines (38 loc) · 1.14 KB
/
openai-handler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { NextRequest } from 'next/server';
const openAiKey = process.env['NX_OPENAI_KEY'];
export const config = {
runtime: 'edge',
};
export default async function handler(request: NextRequest) {
const { action, input } = await request.json();
let apiUrl = 'https://api.openai.com/v1/';
if (action === 'embedding') {
apiUrl += 'embeddings';
} else if (action === 'chatCompletion') {
apiUrl += 'chat/completions';
} else if (action === 'moderation') {
apiUrl += 'moderations';
} else {
return new Response('Invalid action', { status: 400 });
}
try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
Authorization: `Bearer ${openAiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(input),
});
const responseData = await response.json();
return new Response(JSON.stringify(responseData), {
status: response.status,
headers: {
'content-type': 'application/json',
},
});
} catch (e) {
console.error('Error processing the request:', e.message);
return new Response(e.message, { status: 500 });
}
}