forked from openai/openai-realtime-console
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
96 lines (85 loc) · 2.36 KB
/
server.js
File metadata and controls
96 lines (85 loc) · 2.36 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
import express from "express";
import fs from "fs";
import { createServer as createViteServer } from "vite";
import "dotenv/config";
const app = express();
app.use(express.text());
const port = process.env.PORT || 3000;
const apiKey = process.env.OPENAI_API_KEY;
// Configure Vite middleware for React client
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "custom",
});
app.use(vite.middlewares);
const sessionConfig = JSON.stringify({
session: {
type: "realtime",
model: "gpt-realtime",
audio: {
output: {
voice: "marin",
},
},
},
});
// All-in-one SDP request (experimental)
app.post("/session", async (req, res) => {
const fd = new FormData();
console.log(req.body);
fd.set("sdp", req.body);
fd.set("session", sessionConfig);
const r = await fetch("https://api.openai.com/v1/realtime/calls", {
method: "POST",
headers: {
"OpenAI-Beta": "realtime=v1",
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: fd,
});
const sdp = await r.text();
console.log(sdp);
// Send back the SDP we received from the OpenAI REST API
res.send(sdp);
});
// API route for ephemeral token generation
app.get("/token", async (req, res) => {
try {
const response = await fetch(
"https://api.openai.com/v1/realtime/client_secrets",
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: sessionConfig,
},
);
const data = await response.json();
res.json(data);
} catch (error) {
console.error("Token generation error:", error);
res.status(500).json({ error: "Failed to generate token" });
}
});
// Render the React client
app.use("*", async (req, res, next) => {
const url = req.originalUrl;
try {
const template = await vite.transformIndexHtml(
url,
fs.readFileSync("./client/index.html", "utf-8"),
);
const { render } = await vite.ssrLoadModule("./client/entry-server.jsx");
const appHtml = await render(url);
const html = template.replace(`<!--ssr-outlet-->`, appHtml?.html);
res.status(200).set({ "Content-Type": "text/html" }).end(html);
} catch (e) {
vite.ssrFixStacktrace(e);
next(e);
}
});
app.listen(port, () => {
console.log(`Express server running on *:${port}`);
});