-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
176 lines (149 loc) · 4.85 KB
/
Copy pathindex.js
File metadata and controls
176 lines (149 loc) · 4.85 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// This is an express server that proxies requests to the OpenAI API
import express from 'express';
import fetch from 'node-fetch';
import cors from 'cors';
import { pipeline } from 'node:stream';
// For file uploads
import multer from "multer";
import FormData from "form-data";
const app = express();
const port = process.env.PORT || 3000;
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const CORS_ORIGIN = process.env.CORS_ORIGIN;
function parseCorsOrigins(value) {
const trimmed = value?.trim();
if (!trimmed) {
return [];
}
if (trimmed.startsWith("[")) {
try {
const parsed = JSON.parse(trimmed);
if (!Array.isArray(parsed)) {
throw new Error("CORS_ORIGIN JSON value must be an array of origins");
}
return parsed
.map((origin) => String(origin).trim())
.filter(Boolean);
} catch (error) {
throw new Error(`Invalid CORS_ORIGIN JSON array: ${error.message}`);
}
}
return trimmed
.split(",")
.map((origin) => origin.trim())
.filter(Boolean);
}
if (!OPENAI_API_KEY) {
throw new Error('OPENAI_API_KEY environment variable is not set');
}
if (!CORS_ORIGIN) {
throw new Error('CORS_ORIGIN environment variable is not set');
}
const corsOrigins = parseCorsOrigins(CORS_ORIGIN);
if (corsOrigins.length === 0) {
throw new Error("CORS_ORIGIN does not contain any valid origins");
}
app.use(cors({
origin: corsOrigins, // specify allowed origins
}));
app.use(express.json());
app.post('/v1/chat/completions', async (req, res) => {
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`,
},
body: JSON.stringify(req.body),
});
if (!response.ok) {
const errorDetails = await response.text();
return res.status(response.status).send(errorDetails);
}
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Error proxying request to OpenAI API:', error);
res.status(500).send('Internal Server Error');
}
});
// Forward /v1/responses to OpenAI (supports streaming)
app.post("/v1/responses", async (req, res) => {
try {
const upstream = await fetch("https://api.openai.com/v1/responses", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(req.body),
});
const contentType = upstream.headers.get("content-type") || "application/octet-stream";
const wantsStream = req.body?.stream === true;
if (!upstream.ok) {
const errText = await upstream.text();
console.error(
`[responses] upstream non-OK status=${upstream.status} body_preview=${JSON.stringify(errText.slice(0, 300))}`,
);
return res.status(upstream.status).type(contentType).send(errText);
}
if (wantsStream) {
if (!contentType.includes("text/event-stream")) {
const body = await upstream.text();
return res.status(502).json({
error: "Upstream did not return SSE",
contentType,
body,
});
}
res.status(200);
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache, no-transform");
res.setHeader("Connection", "keep-alive");
res.setHeader("X-Accel-Buffering", "no");
res.flushHeaders?.();
if (!upstream.body) {
return res.end();
}
pipeline(upstream.body, res, (err) => {
if (err) {
console.error("SSE pipeline error:", err);
}
});
return;
}
const data = await upstream.text();
return res.status(upstream.status).type(contentType).send(data);
} catch (err) {
console.error("Proxy error (responses):", err);
return res.status(500).json({ error: err?.message || "Internal Server Error" });
}
});
// Forward /v1/files to OpenAI Files API for file uploads
const upload = multer();
app.post("/v1/files", upload.single("file"), async (req, res) => {
try {
const form = new FormData();
form.append("file", req.file.buffer, req.file.originalname);
form.append("purpose", req.body.purpose);
const response = await fetch("https://api.openai.com/v1/files", {
method: "POST",
headers: {
Authorization: `Bearer ${OPENAI_API_KEY}`,
...form.getHeaders(),
},
body: form,
});
const data = await response.json();
res.status(response.status).json(data);
} catch (err) {
console.error("File upload error:", err);
res.status(500).json({ error: err.message });
}
});
app.listen(port, () => {
console.log(`Proxy server listening at http://localhost:${port}`);
});
// To run this server, use the command
// OPENAI_API_KEY=your_api_key_here node index.js