-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
69 lines (55 loc) · 1.99 KB
/
Copy pathserver.js
File metadata and controls
69 lines (55 loc) · 1.99 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
import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import dotenv from "dotenv";
import OpenAI from "openai";
dotenv.config();
const app = express();
const PORT = process.env.PORT ?? 3000;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const apiKey = process.env.OpenAISecretKey;
const openaiClient = apiKey ? new OpenAI({ apiKey }) : null;
app.use(express.json());
app.use(express.static(__dirname));
app.get("/api/status", (_req, res) => {
res.json({ hasOpenAIKey: Boolean(openaiClient) });
});
app.post("/api/fashion-story", async (req, res) => {
if (!openaiClient) {
return res.status(500).json({ error: "Missing OpenAI API key on the server." });
}
const selections = Array.isArray(req.body?.selections) ? req.body.selections : [];
const lookDescription = selections.length
? selections.map((item) => `${item.name} (${item.category})`).join(", ")
: "no accessories yet";
try {
const response = await openaiClient.responses.create({
model: "gpt-4o-mini",
input: [
{
role: "system",
content: "You are a spirited hamster fashion stylist who writes playful runway recaps.",
},
{
role: "user",
content: `Describe the hamster outfit featuring: ${lookDescription}. Keep it to two whimsical sentences.`,
},
],
max_output_tokens: 180,
temperature: 0.8,
});
const story = (response.output_text ?? "").trim();
const fallback = "Our AI stylist is dazzled into silence. Try another combination!";
res.json({ story: story || fallback });
} catch (error) {
console.error("Failed to generate fashion story", error);
res.status(500).json({ error: "Unable to generate story from OpenAI." });
}
});
app.use((_req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
app.listen(PORT, () => {
console.log(`Hamster Fashion server listening on http://localhost:${PORT}`);
});