-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
78 lines (62 loc) · 2.13 KB
/
server.js
File metadata and controls
78 lines (62 loc) · 2.13 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
"use strict";
require("dotenv").config();
const express = require("express");
const { buildClientSecretPayload, buildImageGenerationPayload } = require("./lib/payloads");
const app = express();
const port = Number.parseInt(process.env.PORT || "3000", 10);
const openAiBaseUrl = "https://api.openai.com/v1";
app.use(express.json({ limit: "1mb" }));
app.get("/health", (req, res) => {
res.json({ ok: true });
});
app.post("/realtime/client-secret", async (req, res) => {
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
res.status(500).json({ error: "Missing OPENAI_API_KEY in .env." });
return;
}
const payload = buildClientSecretPayload(req.body);
try {
const response = await fetch(`${openAiBaseUrl}/realtime/client_secrets`, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
const bodyText = await response.text();
res.status(response.status);
res.set("Content-Type", response.headers.get("content-type") || "application/json");
res.send(bodyText);
} catch (error) {
res.status(502).json({ error: error.message || "Failed to reach OpenAI." });
}
});
app.post("/images/generations", async (req, res) => {
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
res.status(500).json({ error: "Missing OPENAI_API_KEY in .env." });
return;
}
const payload = buildImageGenerationPayload(req.body);
try {
const response = await fetch(`${openAiBaseUrl}/images/generations`, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
const bodyText = await response.text();
res.status(response.status);
res.set("Content-Type", response.headers.get("content-type") || "application/json");
res.send(bodyText);
} catch (error) {
res.status(502).json({ error: error.message || "Failed to reach OpenAI." });
}
});
app.listen(port, () => {
console.log(`Realtime backend listening on http://localhost:${port}`);
});