-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
123 lines (105 loc) · 3.21 KB
/
server.js
File metadata and controls
123 lines (105 loc) · 3.21 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
115
116
117
118
119
120
121
122
123
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
require("dotenv").config();
const fs = require("fs");
const { GoogleGenerativeAI } = require("@google/generative-ai");
const app = express();
const PORT = 3000;
// 파일 경로
const HISTORY_FILE = path.join(__dirname, "conversation.json");
const MAX_HISTORY_LENGTH = 10; // 대화 기록 최대 길이 (사용자 질문 + AI 답변 = 1세트)
// 미들웨어
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "public")));
// Gemini 모델 초기화
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
console.error("GEMINI_API_KEY is not set in the .env file.");
process.exit(1);
}
const genAI = new GoogleGenerativeAI(apiKey);
const model = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
});
const generationConfig = {
temperature: 1,
topP: 0.95,
topK: 64,
maxOutputTokens: 8192,
responseMimeType: "text/plain",
};
// 대화 기록 불러오기
function loadHistoryFromFile() {
try {
if (fs.existsSync(HISTORY_FILE)) {
const data = fs.readFileSync(HISTORY_FILE, "utf8");
if (data.trim() === "") {
return [];
}
return JSON.parse(data);
}
} catch (error) {
console.error("Error loading conversation history:", error);
}
return [];
}
// 대화 기록 저장
function saveHistoryToFile(history) {
try {
const historyToSave = history.slice(-MAX_HISTORY_LENGTH * 2);
fs.writeFileSync(HISTORY_FILE, JSON.stringify(historyToSave, null, 2));
} catch (error) {
console.error("Error saving conversation history:", error);
}
}
// 루트 경로
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
// 대화 API
app.post("/ask", async (req, res) => {
try {
const { prompt } = req.body;
if (!prompt) {
return res.status(400).json({ error: "Prompt is missing." });
}
const history = loadHistoryFromFile();
const chatSession = model.startChat({
generationConfig,
history,
});
const result = await chatSession.sendMessage(prompt);
const answer = result.response.text();
console.log("AI Answer:", answer);
const newHistory = [
...history,
{ role: "user", parts: [{ text: prompt }] },
{ role: "model", parts: [{ text: answer }] },
];
saveHistoryToFile(newHistory);
res.status(200).json({ answer });
} catch (error) {
console.error("Error during AI interaction:", error);
if (error.message.includes("API key not valid")) {
return res.status(401).json({ error: "Invalid API key. Please check your .env file." });
}
res.status(500).json({ error: "Internal Server Error" });
}
});
// 대화 기록 조회
app.get("/history", (req, res) => {
try {
const history = loadHistoryFromFile();
res.status(200).json({ history });
} catch (error) {
console.error("Error reading history:", error);
res.status(500).json({ error: "Failed to load history." });
}
});
// 서버 시작
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
console.log("Please set your GEMINI_API_KEY in the .env file.");
});