-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
114 lines (98 loc) · 3.22 KB
/
server.js
File metadata and controls
114 lines (98 loc) · 3.22 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
import "dotenv/config";
import express from "express";
const app = express();
const port = process.env.PORT || 3000;
const apiKey = process.env.OPENAI_API_KEY;
app.use(express.json({ limit: "1mb" }));
app.use(express.static("public"));
app.post("/api/predict", async (req, res) => {
try {
if (!apiKey) {
return res.status(500).json({ error: "Missing OPENAI_API_KEY env var." });
}
const prompt = String(req.body?.prompt ?? "");
if (!prompt.trim()) {
return res.json({ tokens: [] });
}
const response = await fetch("https://api.openai.com/v1/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "gpt-3.5-turbo-instruct",
prompt,
max_tokens: 1,
temperature: 0,
logprobs: Math.max(1, Math.min(15, Number(req.body?.top_k ?? 5))),
top_p: Number(req.body?.top_p ?? 0.9),
}),
});
if (!response.ok) {
const text = await response.text();
return res
.status(response.status)
.json({ error: "OpenAI request failed", details: text });
}
const data = await response.json();
const top = data?.choices?.[0]?.logprobs?.top_logprobs?.[0] || {};
const entries = Object.entries(top).map(([token, logprob]) => ({
token,
logprob,
}));
entries.sort((a, b) => b.logprob - a.logprob);
// Convert logprobs to normalized probabilities over returned candidates.
const maxLogprob = entries[0]?.logprob ?? 0;
const exp = entries.map((e) => Math.exp(e.logprob - maxLogprob));
const sumExp = exp.reduce((a, b) => a + b, 0) || 1;
const tokens = entries.map((e, i) => ({
token: e.token,
prob: exp[i] / sumExp,
}));
res.json({ tokens });
} catch (err) {
res.status(500).json({ error: "Server error", details: String(err) });
}
});
app.post("/api/next", async (req, res) => {
try {
if (!apiKey) {
return res.status(500).json({ error: "Missing OPENAI_API_KEY env var." });
}
const prompt = String(req.body?.prompt ?? "");
const temperature = Number(req.body?.temperature ?? 0);
const maxTokens = Math.max(1, Math.min(5, Number(req.body?.max_tokens ?? 1)));
if (!prompt.trim()) {
return res.json({ token: "" });
}
const response = await fetch("https://api.openai.com/v1/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "gpt-3.5-turbo-instruct",
prompt,
max_tokens: maxTokens,
temperature,
top_p: Number(req.body?.top_p ?? 0.9),
}),
});
if (!response.ok) {
const text = await response.text();
return res
.status(response.status)
.json({ error: "OpenAI request failed", details: text });
}
const data = await response.json();
const token = data?.choices?.[0]?.text ?? "";
res.json({ token });
} catch (err) {
res.status(500).json({ error: "Server error", details: String(err) });
}
});
app.listen(port, () => {
console.log(`Token predictor running at http://localhost:${port}`);
});