-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1861 lines (1644 loc) · 58.6 KB
/
Copy pathserver.js
File metadata and controls
1861 lines (1644 loc) · 58.6 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// server.js
import path from "path";
import fs from "fs";
import fsp from "fs/promises";
import express from "express";
import cors from "cors";
import axios from "axios";
import dotenv from "dotenv";
import multer from "multer";
import { v4 as uuidv4 } from "uuid";
import nodemailer from "nodemailer";
import jwt from "jsonwebtoken";
import bcrypt from "bcryptjs";
import {
ingestFileToDB,
getEmbedding,
extractTextFromFile
} from "./ingest-utils.js";
import {
listDocs,
getAllChunks,
insertChat,
getChats,
clearChats,
deleteHistoryPair,
listDocsWithStats,
getDocById,
getChunksByDoc,
deleteChunkById,
deleteDocCascade,
countChunksForDoc,
createUser,
getUserByUsername,
getUserByEmail,
getUserById,
checkUsernameExists,
checkEmailExists,
createVerificationCode,
verifyCode,
cleanupExpiredCodes,
createBook,
updateBook,
getBookById,
listBooks,
listBooksWithStats,
deleteBook,
createChapter,
updateChapter,
getChapterById,
getChaptersByBook,
deleteChapter,
updateDocChapter,
getDocByChapter,
countChunksForChapter,
getChunksByChapter
} from "./db.js";
dotenv.config();
const app = express();
const port = 3001;
// 确保环境
const REQUIRED_ENVS = ["BASE_URL", "OPENAI_API_KEY"];
for (const key of REQUIRED_ENVS) {
if (!process.env[key]) {
console.warn(`[WARN] ENV ${key} is not set. Please configure it in .env`);
}
}
// 使用 cors 中间件,允许所有来源访问
app.use(
cors({
origin: "*",
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
preflightContinue: false,
optionsSuccessStatus: 204,
})
);
app.use(express.json({ limit: "2mb" }));
app.use(express.urlencoded({ extended: true, limit: "2mb" }));
// JWT密钥
const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key-change-in-production";
// 认证中间件
function authenticateToken(req, res, next) {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (!token) {
return res.status(401).json({ error: true, message: "未提供认证令牌" });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
return res.status(403).json({ error: true, message: "无效的认证令牌" });
}
}
// 可选认证中间件
function optionalAuth(req, res, next) {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (token) {
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
} catch (err) {
}
}
next();
}
// 确保Upload文件夹存在
const UPLOAD_DIR = path.resolve("uploads");
if (!fs.existsSync(UPLOAD_DIR)) {
fs.mkdirSync(UPLOAD_DIR, { recursive: true });
}
// 确保封面文件夹存在
const COVERS_DIR = path.resolve("covers");
if (!fs.existsSync(COVERS_DIR)) {
fs.mkdirSync(COVERS_DIR, { recursive: true });
}
// 静态文件服务(封面图片)
app.use("/covers", express.static(COVERS_DIR));
// 删除操作密码验证中间件
const DELETE_PASSWORD = process.env.DELETE_PASSWORD || "admin123";
function verifyDeletePassword(req, res, next) {
const { password } = req.body || {};
if (password !== DELETE_PASSWORD) {
return res.status(401).json({ ok: false, message: "删除密码错误" });
}
next();
}
// Multer 上传配置
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, UPLOAD_DIR);
},
filename: function (req, file, cb) {
const ext = path.extname(file.originalname || "");
cb(null, `${uuidv4()}${ext}`); // preserve extension
},
});
const upload = multer({
storage,
limits: { fileSize: 50 * 1024 * 1024 }, // 25MB
});
// 余弦相似度函数
function dot(a, b) {
let s = 0;
const n = Math.min(a.length, b.length);
for (let i = 0; i < n; i++) s += a[i] * b[i];
return s;
}
function norm(a) {
return Math.sqrt(dot(a, a));
}
function cosineSim(a, b) {
const denom = norm(a) * norm(b) + 1e-8;
return denom === 0 ? 0 : dot(a, b) / denom;
}
function clampTopK(value, fallback = 5, min = 1, max = 50) {
const n = Number(value);
if (!Number.isFinite(n)) return fallback;
return Math.max(min, Math.min(max, Math.floor(n)));
}
function parseEmbeddingMaybe(s) {
try {
return JSON.parse(s);
} catch {
return null;
}
}
// OpenAI的API包装器
async function postChatCompletion(body) {
const baseURL = process.env.BASE_URL;
const apiKey = process.env.OPENAI_API_KEY;
if (!baseURL || !apiKey) {
throw new Error("Missing BASE_URL or OPENAI_API_KEY");
}
const { data } = await axios.post(`${baseURL}/chat/completions`, body, {
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
timeout: 600_000,
});
return data;
}
// 图片解析
async function chatVision(imagePathOrUrl, prompt = "请解析这张图", model = "gemini-3-pro-preview") {
let imageItem;
if (/^https?:\/\//i.test(imagePathOrUrl)) {
imageItem = { type: "image_url", image_url: { url: imagePathOrUrl } };
} else {
const mime = (await import("mime-types")).default;
const buf = await fsp.readFile(imagePathOrUrl);
const b64 = buf.toString("base64");
const m = mime.lookup(path.extname(imagePathOrUrl)) || "image/png";
imageItem = { type: "image_url", image_url: { url: `data:${m};base64,${b64}` } };
}
const j = await postChatCompletion({
model,
temperature: 0.2,
messages: [
{
role: "user",
content: [{ type: "text", text: prompt }, imageItem],
},
],
});
const content = j?.choices?.[0]?.message?.content;
if (!content) {
throw new Error("Vision API returned empty content");
}
return content;
}
async function recognizeImageContent(imagePath) {
const prompt =
"请对这张图的内容做尽可能详细的描述,保证你的描述能涵盖图片中的所有信息。仅输出该描述,不要输出其他多余内容。";
return chatVision(imagePath, prompt, "gemini-3-pro-preview");
}
// 识别文件内容(提取文本并生成描述)
async function recognizeFileContent(filePath, filename) {
try {
const text = await extractTextFromFile(filePath);
if (!text || !text.trim()) {
return `文件 ${filename} 内容为空或无法提取文本。`;
}
// 生成文件内容描述
const preview = text.slice(0, 5000);
return `文件 ${filename} 的内容如下:\n${preview}${text.length > 5000 ? "\n(文件内容较长,已截取前5000字符)" : ""}`;
} catch (err) {
console.error("File content extraction failed:", err);
return `文件 ${filename} 内容提取失败:${err.message || String(err)}`;
}
}
// RAG 搜索
async function search_rag(query, topK = 5) {
if (!query) return [];
const qEmb = await getEmbedding(query);
const rows = getAllChunks() || [];
if (rows.length === 0) return [];
const scored = rows
.map((r) => {
const emb = parseEmbeddingMaybe(r.embedding);
if (!emb) return null;
return { ...r, score: cosineSim(qEmb, emb) };
})
.filter(Boolean)
.sort((a, b) => b.score - a.score)
.slice(0, clampTopK(topK));
return scored.map((s) => {
// 构建引用来源:书籍名-章节名,如果没有则使用文档名
let sourceName = "";
if (s.book_title && s.chapter_title) {
sourceName = `${s.book_title}-${s.chapter_title}`;
} else if (s.book_title) {
sourceName = s.book_title;
} else if (s.chapter_title) {
sourceName = s.chapter_title;
} else if (s.filename) {
sourceName = s.filename.replace(/\.[^/.]+$/, ""); // 去除扩展名
} else {
sourceName = `文档${s.doc_id || s.id}`;
}
return {
snippet: (s.content || "").slice(0, 1200),
source: sourceName,
book_title: s.book_title || null,
chapter_title: s.chapter_title || null,
filename: s.filename || null,
doc_id: s.doc_id || null,
score: s.score,
};
});
}
// Reaxys API 调用
async function search_reaxys(query) {
const apiKey = process.env.REAXYS_API_KEY;
const apiUrl = process.env.REAXYS_API_URL || "https://api.reaxys.com/v2/api";
if (!apiKey) {
console.warn("[WARN] REAXYS_API_KEY is not set. Reaxys search will be skipped.");
return null;
}
try {
// 实际请根据 Reaxys API 文档调整请求格式
const response = await axios.post(
apiUrl,
{
query: query,
// 可以根据需要添加其他参数
},
{
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
},
timeout: 30_000,
}
);
const data = response.data;
// 需要根据实际 API 返回格式调整,解析 Reaxys 返回结果,转换为与 RAG 类似的格式
if (data && (data.results || data.data || data.hits)) {
const results = data.results || data.data || data.hits || [];
if (Array.isArray(results) && results.length > 0) {
return results.slice(0, 5).map((item, idx) => ({
snippet: (item.text || item.content || item.abstract || JSON.stringify(item)).slice(0, 1200),
source: item.source || item.title || `Reaxys结果${idx + 1}`,
score: item.score || item.relevance || 1.0,
}));
}
}
return null;
} catch (err) {
console.error("Reaxys API error:", err?.response?.data || err?.message || err);
return null;
}
}
// 联网搜索 API 调用
async function search_web(query) {
const apiKey = process.env.TAVILY_API_KEY;
if (!apiKey) {
console.warn("[WARN] TAVILY_API_KEY is not set. Web search will be skipped.");
return null;
}
try {
// 使用 Tavily API
const response = await axios.post(
"https://api.tavily.com/search",
{
query: query,
search_depth: "basic",
max_results: 5,
include_answer: true,
include_raw_content: false,
},
{
headers: { Authorization: `Bearer ${apiKey}`},
timeout: 30_000,
}
);
const data = response.data;
// 解析 Tavily 返回结果
if (data && (data.results || data.answer)) {
const results = [];
// 如果有答案,优先使用
if (data.answer) {
results.push({
snippet: data.answer.slice(0, 1200),
source: "网络搜索答案",
score: 1.0,
});
}
// 添加搜索结果
if (Array.isArray(data.results) && data.results.length > 0) {
data.results.forEach((item) => {
if (item.content) {
results.push({
snippet: item.content.slice(0, 1200),
source: item.title || item.url || "网络搜索结果",
score: item.score || 0.8,
url: item.url || null,
});
}
});
}
if (results.length > 0) {
return results.slice(0, 5);
}
}
return null;
} catch (err) {
console.error("Web search API error:", err?.response?.data || err?.message || err);
// 如果 Tavily 额度不足,尝试 Serper
if (process.env.SERPER_API_KEY) {
try {
const serperResponse = await axios.post(
"https://google.serper.dev/search",
{
q: query,
num: 5,
},
{
headers: {
"X-API-KEY": process.env.SERPER_API_KEY,
"Content-Type": "application/json",
},
timeout: 30_000,
}
);
const serperData = serperResponse.data;
if (serperData && Array.isArray(serperData.organic)) {
return serperData.organic.slice(0, 5).map((item) => ({
snippet: (item.snippet || item.description || "").slice(0, 1200),
source: item.title || item.link || "网络搜索结果",
score: item.position ? 1.0 / (item.position + 1) : 0.8,
url: item.link || null,
}));
}
} catch (serperErr) {
console.error("Serper API error:", serperErr?.response?.data || serperErr?.message);
}
}
return null;
}
}
// 上传并导入文档
app.post("/api/ingest", upload.single("file"), async (req, res) => {
if (!req.file) return res.status(400).json({ error: true, message: "Missing file" });
const fp = req.file.path;
let originalname = req.file.originalname;
const chapterId = req.body?.chapter_id || null;
try {
try {
originalname = Buffer.from(originalname, "latin1").toString("utf8");
} catch (e) {
console.warn("Filename encoding fix failed:", e);
}
const result = await ingestFileToDB(fp, originalname, {
onProgress: ({ total, done }) => {
console.log(`Ingesting ${originalname} : ${done}/${total}`);
},
chapterId, // 传递章节ID
});
// 如果指定了章节ID,更新文档的chapter_id
if (chapterId && result?.docId) {
updateDocChapter(result.docId, chapterId);
}
return res.json({ ok: true, ...result });
} catch (err) {
console.error("Ingest error:", err);
return res.status(500).json({ error: true, message: err.message || String(err) });
} finally {
try {
await fsp.unlink(fp);
} catch {}
}
});
// 列出已导入文档
app.get("/api/docs", (req, res) => {
try {
const docs = listDocs();
res.json(docs);
} catch (err) {
res.status(500).json({ error: true, message: err.message || String(err) });
}
});
// 文档列表 + chunk 数
app.get("/api/docs/stats", (req, res) => {
try {
const docs = listDocsWithStats();
res.json({ ok: true, docs });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 文档详情 + chunk 计数
app.get("/api/doc/:id", (req, res) => {
try {
const id = req.params.id;
const doc = getDocById(id);
if (!doc) return res.status(404).json({ ok: false, message: "Doc not found" });
const chunk_count = countChunksForDoc(id);
res.json({ ok: true, doc: { ...doc, chunk_count } });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 文档 chunks 列表
app.get("/api/doc/:id/chunks", (req, res) => {
try {
const id = req.params.id;
const rows = getChunksByDoc(id) || [];
// 仅返回必要字段,避免 embedding 过大
const chunks = rows.map(r => ({
id: r.id,
content: r.content,
created_at: r.created_at
}));
res.json({ ok: true, chunks });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 删除单个 chunk
app.delete("/api/chunk/:id", (req, res) => {
try {
const id = req.params.id;
const changes = deleteChunkById(id);
if (!changes) return res.status(404).json({ ok: false, message: "Chunk not found" });
res.json({ ok: true, deleted: changes });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 删除整个文档及所有 chunks)
app.delete("/api/doc/:id", verifyDeletePassword, (req, res) => {
try {
const id = req.params.id;
const { delChunks, delDoc } = deleteDocCascade(id);
if (!delDoc) return res.status(404).json({ ok: false, message: "Doc not found" });
res.json({ ok: true, deletedDoc: delDoc, deletedChunks: delChunks });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 书籍相关API
// 获取所有书籍
app.get("/api/books", (req, res) => {
try {
const books = listBooksWithStats();
res.json({ ok: true, books });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 获取单个书籍详情
app.get("/api/book/:id", (req, res) => {
try {
const id = req.params.id;
const book = getBookById(id);
if (!book) return res.status(404).json({ ok: false, message: "Book not found" });
res.json({ ok: true, book });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 创建书籍
app.post("/api/books", (req, res, next) => {
upload.fields([{ name: "cover", maxCount: 1 }])(req, res, (err) => {
if (err) {
console.error("Multer error:", err);
return res.status(400).json({ ok: false, message: err.message || "文件上传失败" });
}
next();
});
}, async (req, res) => {
try {
const { title } = req.body || {};
if (!title || !title.trim()) {
return res.status(400).json({ ok: false, message: "书名不能为空" });
}
const bookId = uuidv4();
let coverPath = null;
// 处理封面上传
if (req.files?.cover?.[0]) {
const coverFile = req.files.cover[0];
const ext = path.extname(coverFile.originalname || "");
const coverFilename = `${bookId}${ext}`;
coverPath = path.join(COVERS_DIR, coverFilename);
await fsp.rename(coverFile.path, coverPath);
coverPath = `/covers/${coverFilename}`; // 返回相对路径
}
createBook(bookId, title.trim(), coverPath);
const book = getBookById(bookId);
res.json({ ok: true, book });
} catch (err) {
console.error("Create book error:", err);
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 更新书籍
app.put("/api/book/:id", (req, res, next) => {
upload.fields([{ name: "cover", maxCount: 1 }])(req, res, (err) => {
if (err) {
console.error("Multer error:", err);
return res.status(400).json({ ok: false, message: err.message || "文件上传失败" });
}
next();
});
}, async (req, res) => {
try {
const id = req.params.id;
const title = req.body?.title;
const book = getBookById(id);
if (!book) {
return res.status(404).json({ ok: false, message: "Book not found" });
}
let coverPath = book.cover_path;
// 如果上传了新封面,替换旧封面
if (req.files?.cover?.[0]) {
// 删除旧封面
if (coverPath && coverPath.startsWith("/covers/")) {
const oldCoverPath = path.join(process.cwd(), coverPath);
try {
await fsp.unlink(oldCoverPath);
} catch (e) {
console.warn("Failed to delete old cover:", e);
}
}
const coverFile = req.files.cover[0];
const ext = path.extname(coverFile.originalname || "");
const coverFilename = `${id}${ext}`;
const newCoverPath = path.join(COVERS_DIR, coverFilename);
try {
await fsp.rename(coverFile.path, newCoverPath);
coverPath = `/covers/${coverFilename}`;
} catch (e) {
console.error("Failed to save cover:", e);
// 如果保存失败,尝试删除临时文件
try {
await fsp.unlink(coverFile.path);
} catch {}
return res.status(500).json({ ok: false, message: "保存封面失败" });
}
}
const newTitle = (title && title.trim()) || book.title;
updateBook(id, newTitle, coverPath);
const updatedBook = getBookById(id);
res.json({ ok: true, book: updatedBook });
} catch (err) {
console.error("Update book error:", err);
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 删除书籍
app.delete("/api/book/:id", verifyDeletePassword, (req, res) => {
try {
const id = req.params.id;
// 先获取书籍信息
const book = getBookById(id);
if (!book) return res.status(404).json({ ok: false, message: "Book not found" });
// 删除封面文件
if (book.cover_path && book.cover_path.startsWith("/covers/")) {
const coverPath = path.join(process.cwd(), book.cover_path);
fsp.unlink(coverPath).catch(() => {});
}
// 删除书籍
const deleted = deleteBook(id);
if (!deleted) return res.status(404).json({ ok: false, message: "Book not found" });
res.json({ ok: true, deleted: true });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 章节相关API
// 获取书籍的所有章节
app.get("/api/book/:bookId/chapters", (req, res) => {
try {
const bookId = req.params.bookId;
const chapters = getChaptersByBook(bookId);
// 为每个章节添加分块数统计
const chaptersWithStats = chapters.map(ch => {
const chunkCount = countChunksForChapter(ch.id);
return { ...ch, chunk_count: chunkCount };
});
res.json({ ok: true, chapters: chaptersWithStats });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 获取单个章节详情
app.get("/api/chapter/:id", (req, res) => {
try {
const id = req.params.id;
const chapter = getChapterById(id);
if (!chapter) return res.status(404).json({ ok: false, message: "Chapter not found" });
const chunkCount = countChunksForChapter(id);
res.json({ ok: true, chapter: { ...chapter, chunk_count: chunkCount } });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 创建章节
app.post("/api/chapters", async (req, res) => {
try {
const { book_id, title, order_index } = req.body || {};
if (!book_id || !title || !title.trim()) {
return res.status(400).json({ ok: false, message: "书籍ID和章节标题不能为空" });
}
// 验证书籍存在
const book = getBookById(book_id);
if (!book) {
return res.status(404).json({ ok: false, message: "书籍不存在" });
}
const chapterId = uuidv4();
const order = order_index !== undefined ? parseInt(order_index) : 0;
createChapter(chapterId, book_id, title.trim(), order);
const chapter = getChapterById(chapterId);
res.json({ ok: true, chapter });
} catch (err) {
console.error("Create chapter error:", err);
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 更新章节
app.put("/api/chapter/:id", async (req, res) => {
try {
const id = req.params.id;
const { title, order_index } = req.body || {};
const chapter = getChapterById(id);
if (!chapter) return res.status(404).json({ ok: false, message: "Chapter not found" });
const newTitle = title?.trim() || chapter.title;
const newOrder = order_index !== undefined ? parseInt(order_index) : chapter.order_index;
updateChapter(id, newTitle, newOrder);
const updatedChapter = getChapterById(id);
res.json({ ok: true, chapter: updatedChapter });
} catch (err) {
console.error("Update chapter error:", err);
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 删除章节
app.delete("/api/chapter/:id", verifyDeletePassword, (req, res) => {
try {
const id = req.params.id;
const deleted = deleteChapter(id);
if (!deleted) return res.status(404).json({ ok: false, message: "Chapter not found" });
res.json({ ok: true, deleted: true });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 章节分块相关API
// 获取章节的所有chunks
app.get("/api/chapter/:id/chunks", (req, res) => {
try {
const id = req.params.id;
const rows = getChunksByChapter(id) || [];
const chunks = rows.map(r => ({
id: r.id,
content: r.content,
created_at: r.created_at
}));
res.json({ ok: true, chunks });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 删除单个 chunk
app.delete("/api/chunk/:id", verifyDeletePassword, (req, res) => {
try {
const id = req.params.id;
const changes = deleteChunkById(id);
if (!changes) return res.status(404).json({ ok: false, message: "Chunk not found" });
res.json({ ok: true, deleted: changes });
} catch (err) {
res.status(500).json({ ok: false, message: err.message || String(err) });
}
});
// 检索接口
app.post("/api/search", async (req, res) => {
const { query, topK = 5 } = req.body || {};
if (!query) return res.status(400).json({ error: true, message: "Missing query" });
try {
const qEmb = await getEmbedding(query);
const rows = getAllChunks() || [];
const scored = rows
.map((r) => {
const emb = parseEmbeddingMaybe(r.embedding);
if (!emb) return null;
return { ...r, score: cosineSim(qEmb, emb) };
})
.filter(Boolean)
.sort((a, b) => b.score - a.score)
.slice(0, clampTopK(topK));
res.json({ query, topK: clampTopK(topK), results: scored });
} catch (err) {
console.error("Search error:", err);
res.status(500).json({ error: true, message: err.message || String(err) });
}
});
// 回答问题接口(智能 Agent + 自动 RAG)
app.post("/api/solve", upload.fields([{ name: "image", maxCount: 1 }, { name: "file", maxCount: 1 }]), async (req, res) => {
let imagePath = req.files?.image?.[0]?.path || null;
let filePath = req.files?.file?.[0]?.path || null;
let fileInfo = req.files?.file?.[0] || null;
let results = [];
// 从答案里提取被引用的编号顺序
function extractCitationOrder(answer, maxIndex) {
if (!answer || !maxIndex) return [];
const order = [];
const seen = new Set();
const supRegex = /\$\^\{([^}]*)\}\$/g; // 捕获 $^{ ... }$
let m;
const add = (n) => {
const k = Number(n);
if (Number.isFinite(k) && k >= 1 && k <= maxIndex && !seen.has(k)) {
seen.add(k);
order.push(k);
}
};
while ((m = supRegex.exec(answer)) !== null) {
const inside = m[1] || "";
// 范围 [a-b]
const rangeRe = /\[(\d+)\s*[-–—]\s*(\d+)\]/g;
let r;
while ((r = rangeRe.exec(inside)) !== null) {
const a = parseInt(r[1], 10);
const b = parseInt(r[2], 10);
if (Number.isFinite(a) && Number.isFinite(b)) {
if (a <= b) {
for (let k = a; k <= b; k++) add(k);
} else {
for (let k = a; k >= b; k--) add(k);
}
}
}
// 单个 [n]
const singleRe = /\[(\d+)\]/g;
let s;
while ((s = singleRe.exec(inside)) !== null) {
add(parseInt(s[1], 10));
}
}
return order;
}
try {
// 基础入参与校验
const questionRaw = req.body?.question;
const question = typeof questionRaw === "string" ? questionRaw.trim() : "";
// 从token中获取user_id,如果没有则使用session_id
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
let user_id = null;
let session_id = req.body?.session_id || "default";
if (token) {
try {
const decoded = jwt.verify(token, JWT_SECRET);
user_id = decoded.userId;
session_id = `user_${user_id}`; // 使用user_id作为session_id
} catch (err) {
// token无效,继续使用session_id
}
}
if (!question && !imagePath && !filePath) {
return res
.status(400)
.json({ error: true, message: "Missing question, image or file" });
}
// 如有图片,先做识别,用于数据库记录,不直接发给模型
let imageDescription = "";
if (imagePath) {
try {
imageDescription = await recognizeImageContent(imagePath);
} catch (e) {
console.warn(
"Image recognition failed, will continue without it:",
e?.message || e
);
}
}
// 如有文件,先提取文本内容
let fileDescription = "";
if (filePath && fileInfo) {
try {
let originalname = fileInfo.originalname;
try {
originalname = Buffer.from(originalname, "latin1").toString("utf8");
} catch (e) {
console.warn("Filename encoding fix failed:", e);
}
fileDescription = await recognizeFileContent(filePath, originalname);
} catch (e) {
console.warn(
"File content extraction failed, will continue without it:",
e?.message || e
);
}
}
// 存储使用的完整问题(文本 + 识别描述)
let fullQuestion = question || "";
if (imageDescription) {
fullQuestion = fullQuestion ? `${fullQuestion}\n${imageDescription}` : imageDescription;
}
if (fileDescription) {
fullQuestion = fullQuestion ? `${fullQuestion}\n${fileDescription}` : fileDescription;
}
// 近期对话历史
const history =
(getChats(session_id, 10, user_id) || []).map((h) => ({
role: h.role,
content: h.content,
})) || [];
// 基础指令
const baseMessages = [
{
role: "system",
content: `你是大学有机化学助教,需要为学生提供详细、有条理的解答。请遵循以下要求:
1. 回答必须清晰分段,包含必要的反应方程式、机理解释、实验条件、区域/立体选择性原因、常见错误与总结。
2. 不要输出任何图片,仅使用文字或 LaTeX 格式书写化学式和方程式。
3. 若需要用到后面给你的检索到的相关知识,请在回答中严格使用 KaTeX 上标形式标注参考编号,例如:$^{[1][2]}$;
当编号前也为LaTex公式时,请同时包裹公式与编号,例如:$77.1^\circ\mathrm{C}^{[1][3][5]}$。
不要写“根据检索到的相关知识”这种措辞,直接输出你的回答,并在相关内容处标注引用编号即可。`,
},
...history,
];
// 复用的 data URL(用于两次调用都能带上图片)
let imageDataUrl = "";
if (imagePath) {
const mimeTypes = (await import("mime-types")).default;
const buf = await fsp.readFile(imagePath);
const b64 = buf.toString("base64");
const m = mimeTypes.lookup(imagePath) || "image/png";
imageDataUrl = `data:${m};base64,${b64}`;
}
// 提取文件完整内容
let fileContent = "";
if (filePath) {