-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
72 lines (57 loc) · 1.58 KB
/
server.js
File metadata and controls
72 lines (57 loc) · 1.58 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
require("dotenv").config();
const express = require("express");
const path = require("path");
const OpenAI = require("openai");
const app = express();
const PORT = process.env.PORT || 3000;
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
// Health check route
app.get("/health", (req, res) => {
res.json({ status: "OK", message: "Anish AI running." });
});
app.post("/chat", async (req, res) => {
try {
const userMessage = req.body.message;
if (!userMessage || userMessage.trim() === "") {
return res.status(400).json({ reply: "Message cannot be empty." });
}
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [
{
role: "system",
content: "You are Anish AI, a smart, friendly and helpful assistant."
},
{
role: "user",
content: userMessage
}
],
temperature: 0.7
});
const botReply = completion.choices[0].message.content;
res.json({ reply: botReply });
} catch (error) {
console.error("OpenAI Error:", error.message);
res.status(500).json({
reply: "Anish AI is thinking...try again!"
});
}
});
// 404 fallback
app.use((req, res) => {
res.status(404).json({ message: "Route not found" });
});
function startServer() {
return app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
}
if (require.main === module) {
startServer();
}
module.exports = { startServer };