-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.js
More file actions
67 lines (54 loc) · 2.08 KB
/
Copy pathnode.js
File metadata and controls
67 lines (54 loc) · 2.08 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
import express from "express";
import cors from "cors";
import fetch from "node-fetch";
import dotenv from "dotenv";
dotenv.config();
const app = express();
const PORT = 3000;
// Middleware
app.use(cors());
app.use(express.json());
// API Key cho OpenAI (lấy từ biến môi trường)
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
app.get("/", (req, res) => {
res.send("Welcome to the Chatbot API!");
});
app.post("/chatbot", async (req, res) => {
try {
const { message } = req.body;
if (!message || message.trim() === "") {
return res.status(400).json({ error: "Message không hợp lệ" });
}
// Gọi API OpenAI
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: "gpt-3.5-turbo", // Hoặc "gpt-4"
messages: [
{ role: "system", content: "Bạn là một chatbot chuyên hỗ trợ về phần mềm và phần cứng cho người dùng. Hãy tập trung vào chuyên môn đừng trả lời những câu hỏi không liên quan đến chuyên môn của mình và trả về những câu trả lời thật chi tiết cho các vấn đề của khách hàng." },
{ role: "user", content: message }],
max_tokens: 3000,
}),
});
const data = await response.json();
// Kiểm tra lỗi từ API OpenAI
if (!response.ok) {
return res.status(response.status).json({
error: data.error?.message || "Đã có lỗi xảy ra từ API OpenAI",
});
}
// Trả về câu trả lời từ OpenAI
res.json({ reply: data.choices[0].message.content.trim() });
} catch (error) {
console.error("Error calling OpenAI API:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
// Khởi chạy server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});