Spaces:
Running
Running
Upload 64 files
Browse files- ai-context.js +30 -242
- ai-routes.js +197 -415
- ai-tools.js +150 -0
ai-context.js
CHANGED
|
@@ -1,8 +1,5 @@
|
|
| 1 |
|
| 2 |
-
const {
|
| 3 |
-
User, Student, Score, AttendanceModel, ClassModel,
|
| 4 |
-
LeaveRequestModel, TodoModel, School, Course
|
| 5 |
-
} = require('./models');
|
| 6 |
|
| 7 |
/**
|
| 8 |
* 格式化当前日期
|
|
@@ -14,259 +11,50 @@ const getCurrentDateInfo = () => {
|
|
| 14 |
};
|
| 15 |
|
| 16 |
/**
|
| 17 |
-
* 构建
|
| 18 |
-
*
|
| 19 |
-
|
| 20 |
-
const student = await Student.findOne({
|
| 21 |
-
$or: [{ studentNo: username }, { name: username }],
|
| 22 |
-
schoolId
|
| 23 |
-
});
|
| 24 |
-
|
| 25 |
-
if (!student) return "无法找到该学生的详细档案。";
|
| 26 |
-
|
| 27 |
-
// 1. 获取近期成绩 (最近10条,让AI掌握更多趋势)
|
| 28 |
-
const recentScores = await Score.find({
|
| 29 |
-
studentNo: student.studentNo,
|
| 30 |
-
schoolId
|
| 31 |
-
}).sort({ _id: -1 }).limit(10);
|
| 32 |
-
|
| 33 |
-
// 2. 获取考勤概况
|
| 34 |
-
const attendanceStats = await AttendanceModel.aggregate([
|
| 35 |
-
{ $match: { studentId: student._id.toString() } },
|
| 36 |
-
{ $group: { _id: "$status", count: { $sum: 1 } } }
|
| 37 |
-
]);
|
| 38 |
-
const absentCount = attendanceStats.find(a => a._id === 'Absent')?.count || 0;
|
| 39 |
-
const leaveCount = attendanceStats.find(a => a._id === 'Leave')?.count || 0;
|
| 40 |
-
|
| 41 |
-
// 3. 获取待办事项
|
| 42 |
-
const user = await User.findOne({ username, schoolId });
|
| 43 |
-
const todos = user ? await TodoModel.find({ userId: user._id, isCompleted: false }).limit(5) : [];
|
| 44 |
-
|
| 45 |
-
let prompt = `
|
| 46 |
-
### 当前用户身份:学生 (个人视图)
|
| 47 |
-
- **姓名**: ${student.name}
|
| 48 |
-
- **班级**: ${student.className}
|
| 49 |
-
- **学号**: ${student.studentNo}
|
| 50 |
-
- **积分(小红花)**: ${student.flowerBalance} 🌺
|
| 51 |
-
|
| 52 |
-
### 个人学习数据
|
| 53 |
-
`;
|
| 54 |
-
|
| 55 |
-
if (recentScores.length > 0) {
|
| 56 |
-
prompt += `- **近期成绩历史**: ${recentScores.map(s => `${s.courseName}: ${s.score} (${s.type || '考试'})`).join('; ')}\n`;
|
| 57 |
-
// 计算简单平均分
|
| 58 |
-
const avg = (recentScores.reduce((acc, s) => acc + s.score, 0) / recentScores.length).toFixed(1);
|
| 59 |
-
prompt += `- **近期平均分**: ${avg}\n`;
|
| 60 |
-
} else {
|
| 61 |
-
prompt += `- **近期成绩**: 暂无记录\n`;
|
| 62 |
-
}
|
| 63 |
-
|
| 64 |
-
if (absentCount > 0 || leaveCount > 0) {
|
| 65 |
-
prompt += `- **考勤异常**: 本学期缺勤 ${absentCount} 次,请假 ${leaveCount} 次。\n`;
|
| 66 |
-
} else {
|
| 67 |
-
prompt += `- **考勤状况**: 全勤,表现极佳。\n`;
|
| 68 |
-
}
|
| 69 |
-
|
| 70 |
-
if (todos.length > 0) {
|
| 71 |
-
prompt += `- **未完成待办**: ${todos.map(t => t.content).join('; ')}\n`;
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
return prompt;
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
/**
|
| 78 |
-
* 构建教师画像上下文 (增强版 - 智能区分班主任与科任视角)
|
| 79 |
-
*/
|
| 80 |
-
async function buildTeacherContext(username, schoolId) {
|
| 81 |
-
const user = await User.findOne({ username, schoolId });
|
| 82 |
-
if (!user) return "无法找到该教师档案。";
|
| 83 |
-
|
| 84 |
-
// 1. 确定老师的身份范围
|
| 85 |
-
const homeroomClassName = user.homeroomClass; // 班主任班级
|
| 86 |
-
|
| 87 |
-
// 查找该老师任教的所有课程 (找出任教的其他班级)
|
| 88 |
-
const teachingCourses = await Course.find({
|
| 89 |
-
$or: [{ teacherId: user._id }, { teacherName: user.trueName || user.username }],
|
| 90 |
-
schoolId
|
| 91 |
-
});
|
| 92 |
-
|
| 93 |
-
// 构建任教班级 -> 科目列表的映射 (e.g., "三年级(2)班": ["数学", "科学"])
|
| 94 |
-
const teachingMap = {};
|
| 95 |
-
teachingCourses.forEach(c => {
|
| 96 |
-
if (!teachingMap[c.className]) teachingMap[c.className] = new Set();
|
| 97 |
-
teachingMap[c.className].add(c.courseName);
|
| 98 |
-
});
|
| 99 |
-
|
| 100 |
-
// 合并所有相关班级 (班主任班级 + 任课班级)
|
| 101 |
-
const allClasses = new Set(Object.keys(teachingMap));
|
| 102 |
-
if (homeroomClassName) allClasses.add(homeroomClassName);
|
| 103 |
-
|
| 104 |
-
if (allClasses.size === 0) {
|
| 105 |
-
return `### 当前用户身份:教师\n- **姓名**: ${user.trueName || username}\n- **状态**: 暂未绑定任何班级或课程数据。`;
|
| 106 |
-
}
|
| 107 |
-
|
| 108 |
-
let prompt = `
|
| 109 |
-
### 当前用户身份:教师
|
| 110 |
-
- **姓名**: ${user.trueName || username}
|
| 111 |
-
- **负责班级**: ${Array.from(allClasses).join(', ')}
|
| 112 |
-
`;
|
| 113 |
-
|
| 114 |
-
// 2. 遍历所有相关班级,构建详细数据
|
| 115 |
-
for (const className of allClasses) {
|
| 116 |
-
const isHomeroom = className === homeroomClassName;
|
| 117 |
-
const subjectsTaught = teachingMap[className] ? Array.from(teachingMap[className]) : [];
|
| 118 |
-
|
| 119 |
-
prompt += `\n#### 🏫 班级: ${className} (${isHomeroom ? '我是班主任' : '我是任课老师'})\n`;
|
| 120 |
-
if (!isHomeroom) {
|
| 121 |
-
prompt += `(非班主任视角:仅展示我任教的科目 [${subjectsTaught.join(', ')}] 的数据)\n`;
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
// 2.1 获取该班学生
|
| 125 |
-
const students = await Student.find({ className, schoolId });
|
| 126 |
-
if (students.length === 0) {
|
| 127 |
-
prompt += `- 暂无学生数据\n`;
|
| 128 |
-
continue;
|
| 129 |
-
}
|
| 130 |
-
|
| 131 |
-
const studentNos = students.map(s => s.studentNo);
|
| 132 |
-
const studentIds = students.map(s => s._id.toString());
|
| 133 |
-
|
| 134 |
-
// 2.2 获取考勤 (全班)
|
| 135 |
-
const attendanceRaw = await AttendanceModel.aggregate([
|
| 136 |
-
{ $match: { studentId: { $in: studentIds }, status: { $in: ['Absent', 'Leave'] } } },
|
| 137 |
-
{ $group: { _id: "$studentId", absent: { $sum: { $cond: [{ $eq: ["$status", "Absent"] }, 1, 0] } }, leave: { $sum: { $cond: [{ $eq: ["$status", "Leave"] }, 1, 0] } } } }
|
| 138 |
-
]);
|
| 139 |
-
const attendanceMap = {};
|
| 140 |
-
attendanceRaw.forEach(a => attendanceMap[a._id] = a);
|
| 141 |
-
|
| 142 |
-
// 2.3 获取成绩 (按需获取)
|
| 143 |
-
// 查询该班级学生的所有成绩
|
| 144 |
-
// 为了性能,还是查出来再内存过滤,比多次DB查询快
|
| 145 |
-
const allScores = await Score.find({
|
| 146 |
-
schoolId,
|
| 147 |
-
studentNo: { $in: studentNos }
|
| 148 |
-
}).sort({ _id: -1 }); // 最新的在前
|
| 149 |
-
|
| 150 |
-
// 构建每个学生的成绩摘要
|
| 151 |
-
const studentDetails = students.map(s => {
|
| 152 |
-
const att = attendanceMap[s._id.toString()] || { absent: 0, leave: 0 };
|
| 153 |
-
|
| 154 |
-
// 筛选该学生的成绩
|
| 155 |
-
let myScores = allScores.filter(sc => sc.studentNo === s.studentNo);
|
| 156 |
-
|
| 157 |
-
// 【关键逻辑】过滤显示哪些科目
|
| 158 |
-
if (!isHomeroom) {
|
| 159 |
-
// 如果不是班主任,只保留我教的科目的成绩
|
| 160 |
-
myScores = myScores.filter(sc => subjectsTaught.includes(sc.courseName));
|
| 161 |
-
}
|
| 162 |
-
|
| 163 |
-
// 【聚合逻辑】每个科目只取最近一次成绩 (去重)
|
| 164 |
-
const latestSubjectScores = {};
|
| 165 |
-
myScores.forEach(sc => {
|
| 166 |
-
if (!latestSubjectScores[sc.courseName]) {
|
| 167 |
-
latestSubjectScores[sc.courseName] = sc;
|
| 168 |
-
}
|
| 169 |
-
});
|
| 170 |
-
|
| 171 |
-
const finalScores = Object.values(latestSubjectScores);
|
| 172 |
-
|
| 173 |
-
// 格式化成绩字符串
|
| 174 |
-
let scoreStr = "";
|
| 175 |
-
if (finalScores.length > 0) {
|
| 176 |
-
scoreStr = finalScores.map(sc => `${sc.courseName}:${sc.score}`).join(', ');
|
| 177 |
-
} else {
|
| 178 |
-
scoreStr = "无相关成绩";
|
| 179 |
-
}
|
| 180 |
-
|
| 181 |
-
// 标记异常 (缺勤多 或 有不及格)
|
| 182 |
-
const hasIssue = att.absent > 0 || finalScores.some(sc => sc.score < 60);
|
| 183 |
-
const flag = hasIssue ? "⚠️" : "";
|
| 184 |
-
|
| 185 |
-
return `- ${flag} **${s.name}**: 考勤[缺${att.absent}/假${att.leave}], 小红花:${s.flowerBalance}, 最新成绩:[${scoreStr}]`;
|
| 186 |
-
});
|
| 187 |
-
|
| 188 |
-
// 将学生列表加入 Prompt (限制长度,如果班级人太多,可能需要截断,但Gemini窗口大,通常没事)
|
| 189 |
-
prompt += studentDetails.join('\n') + '\n';
|
| 190 |
-
|
| 191 |
-
// 2.4 如果是班主任,额外显示待办
|
| 192 |
-
if (isHomeroom) {
|
| 193 |
-
const pendingLeaves = await LeaveRequestModel.countDocuments({ className, schoolId, status: 'Pending' });
|
| 194 |
-
if (pendingLeaves > 0) {
|
| 195 |
-
prompt += `> 🔴 班务提醒: 有 ${pendingLeaves} 条请假申请待审批。\n`;
|
| 196 |
-
}
|
| 197 |
-
}
|
| 198 |
-
}
|
| 199 |
-
|
| 200 |
-
return prompt;
|
| 201 |
-
}
|
| 202 |
-
|
| 203 |
-
/**
|
| 204 |
-
* 构建管理员/校长画像上下文
|
| 205 |
-
*/
|
| 206 |
-
async function buildAdminContext(role, schoolId) {
|
| 207 |
-
let prompt = `### 当前用户身份:${role === 'PRINCIPAL' ? '校长' : '超级管理员'}\n`;
|
| 208 |
-
|
| 209 |
-
if (role === 'PRINCIPAL' && schoolId) {
|
| 210 |
-
const school = await School.findById(schoolId);
|
| 211 |
-
const totalStudents = await Student.countDocuments({ schoolId });
|
| 212 |
-
const totalTeachers = await User.countDocuments({ schoolId, role: 'TEACHER' });
|
| 213 |
-
|
| 214 |
-
// 今日缺勤详细名单
|
| 215 |
-
const today = new Date().toISOString().split('T')[0];
|
| 216 |
-
const absences = await AttendanceModel.find({ schoolId, date: today, status: { $in: ['Absent', 'Leave'] } });
|
| 217 |
-
const absentNames = absences.map(a => `${a.studentName}(${a.className})`).join(', ');
|
| 218 |
-
|
| 219 |
-
// 全校均分
|
| 220 |
-
const recentScores = await Score.find({ schoolId }).sort({_id:-1}).limit(100);
|
| 221 |
-
let avgScore = 0;
|
| 222 |
-
if (recentScores.length) avgScore = (recentScores.reduce((a,b)=>a+b.score,0)/recentScores.length).toFixed(1);
|
| 223 |
-
|
| 224 |
-
prompt += `- **学校**: ${school ? school.name : '未知'}\n`;
|
| 225 |
-
prompt += `- **宏观数据**: 教师 ${totalTeachers} 人,学生 ${totalStudents} 人,近期全校抽样平均分 ${avgScore}。\n`;
|
| 226 |
-
prompt += `- **今日出勤**: 缺勤/请假 ${absences.length} 人。名单: ${absentNames || '无'}。\n`;
|
| 227 |
-
}
|
| 228 |
-
|
| 229 |
-
return prompt;
|
| 230 |
-
}
|
| 231 |
-
|
| 232 |
-
/**
|
| 233 |
-
* 主入口:构建用户上下文 Prompt
|
| 234 |
-
* @param {string} username - 请求头中的用户名
|
| 235 |
-
* @param {string} role - 请求头中的角色
|
| 236 |
-
* @param {string} schoolId - 请求头中的学校ID
|
| 237 |
*/
|
| 238 |
async function buildUserContext(username, role, schoolId) {
|
| 239 |
try {
|
| 240 |
const dateStr = getCurrentDateInfo();
|
| 241 |
-
let
|
| 242 |
|
|
|
|
| 243 |
if (role === 'STUDENT') {
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
} else if (role === 'TEACHER') {
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
| 249 |
}
|
| 250 |
|
| 251 |
-
// 组装最终 System Instruction 片段
|
| 252 |
return `
|
| 253 |
---
|
| 254 |
-
【
|
| 255 |
-
当前
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
5. 数据格式说明: [科目:分数] 代表该科目最近一次录入的成绩。
|
| 265 |
---
|
| 266 |
`;
|
| 267 |
} catch (e) {
|
| 268 |
console.error("Context build failed:", e);
|
| 269 |
-
return "";
|
| 270 |
}
|
| 271 |
}
|
| 272 |
|
|
|
|
| 1 |
|
| 2 |
+
const { User, Student, School } = require('./models');
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
/**
|
| 5 |
* 格式化当前日期
|
|
|
|
| 11 |
};
|
| 12 |
|
| 13 |
/**
|
| 14 |
+
* 构建用户上下文 - Agentic版 (精简)
|
| 15 |
+
* 既然 AI 现在有了 query_database 工具,我们不需要把所有数据都塞进 System Prompt。
|
| 16 |
+
* 我们只需要告诉它:“你是谁”,“用户是谁”,以及“你有查库的能力”。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
*/
|
| 18 |
async function buildUserContext(username, role, schoolId) {
|
| 19 |
try {
|
| 20 |
const dateStr = getCurrentDateInfo();
|
| 21 |
+
let userProfile = "";
|
| 22 |
|
| 23 |
+
// 基础用户信息
|
| 24 |
if (role === 'STUDENT') {
|
| 25 |
+
const student = await Student.findOne({
|
| 26 |
+
$or: [{ studentNo: username }, { name: username }],
|
| 27 |
+
schoolId
|
| 28 |
+
});
|
| 29 |
+
if (student) {
|
| 30 |
+
userProfile = `用户是学生:${student.name} (班级: ${student.className}, 学号: ${student.studentNo})`;
|
| 31 |
+
}
|
| 32 |
} else if (role === 'TEACHER') {
|
| 33 |
+
const user = await User.findOne({ username, schoolId });
|
| 34 |
+
if (user) {
|
| 35 |
+
userProfile = `用户是教师:${user.trueName || username} (任教: ${user.teachingSubject || '无'}, 班主任: ${user.homeroomClass || '否'})`;
|
| 36 |
+
}
|
| 37 |
+
} else {
|
| 38 |
+
userProfile = `用户是管理员/校长。`;
|
| 39 |
}
|
| 40 |
|
|
|
|
| 41 |
return `
|
| 42 |
---
|
| 43 |
+
【系统信息】
|
| 44 |
+
当前时间: ${dateStr}
|
| 45 |
+
${userProfile}
|
| 46 |
+
|
| 47 |
+
【能力说明】
|
| 48 |
+
1. 你是一个拥有“本地数据库查询权限”的智能助教。
|
| 49 |
+
2. 工具执行环境:**工具是在用户的本地服务器上执行的**。你可以通过 Function Calling 获取内网数据,**不需要**公网访问权限。
|
| 50 |
+
3. 如果用户问“张三考了多少分”或“我们班谁考勤不好”,请**务必**大胆调用 \`query_database\` 工具。
|
| 51 |
+
4. 不要回答“我无法访问数据库”,因为工具会帮你完成访问并将结果传回给你。
|
| 52 |
+
5. 如果查询结果返回 JSON 数据,请将其整理为通俗易懂的自然语言回答用户。
|
|
|
|
| 53 |
---
|
| 54 |
`;
|
| 55 |
} catch (e) {
|
| 56 |
console.error("Context build failed:", e);
|
| 57 |
+
return "";
|
| 58 |
}
|
| 59 |
}
|
| 60 |
|
ai-routes.js
CHANGED
|
@@ -4,8 +4,8 @@ const router = express.Router();
|
|
| 4 |
const OpenAI = require('openai');
|
| 5 |
const { ConfigModel, User, AIUsageModel, ChatHistoryModel } = require('./models');
|
| 6 |
const { buildUserContext } = require('./ai-context');
|
|
|
|
| 7 |
|
| 8 |
-
// ... (Key Management, Usage Tracking, Helpers remain same)
|
| 9 |
// Fetch keys from DB + merge with ENV variables
|
| 10 |
async function getKeyPool(type) {
|
| 11 |
const config = await ConfigModel.findOne({ key: 'main' });
|
|
@@ -26,266 +26,6 @@ async function recordUsage(model, provider) {
|
|
| 26 |
} catch (e) { console.error("Failed to record AI usage stats:", e); }
|
| 27 |
}
|
| 28 |
|
| 29 |
-
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
| 30 |
-
async function callAIWithRetry(aiModelCall, retries = 1) {
|
| 31 |
-
for (let i = 0; i < retries; i++) {
|
| 32 |
-
try { return await aiModelCall(); }
|
| 33 |
-
catch (e) {
|
| 34 |
-
if (e.status === 400 || e.status === 401 || e.status === 403) throw e;
|
| 35 |
-
if (i < retries - 1) { await wait(1000 * Math.pow(2, i)); continue; }
|
| 36 |
-
throw e;
|
| 37 |
-
}
|
| 38 |
-
}
|
| 39 |
-
}
|
| 40 |
-
|
| 41 |
-
function convertGeminiToOpenAI(baseParams) {
|
| 42 |
-
const messages = [];
|
| 43 |
-
if (baseParams.config?.systemInstruction) messages.push({ role: 'system', content: baseParams.config.systemInstruction });
|
| 44 |
-
|
| 45 |
-
let contents = baseParams.contents;
|
| 46 |
-
if (contents && !Array.isArray(contents)) {
|
| 47 |
-
contents = [contents];
|
| 48 |
-
}
|
| 49 |
-
|
| 50 |
-
if (contents && Array.isArray(contents)) {
|
| 51 |
-
contents.forEach(content => {
|
| 52 |
-
let role = (content.role === 'model' || content.role === 'assistant') ? 'assistant' : 'user';
|
| 53 |
-
const messageContent = [];
|
| 54 |
-
if (content.parts) {
|
| 55 |
-
content.parts.forEach(p => {
|
| 56 |
-
if (p.text) messageContent.push({ type: 'text', text: p.text });
|
| 57 |
-
else if (p.inlineData && p.inlineData.mimeType.startsWith('image/')) {
|
| 58 |
-
messageContent.push({ type: 'image_url', image_url: { url: `data:${p.inlineData.mimeType};base64,${p.inlineData.data}` } });
|
| 59 |
-
}
|
| 60 |
-
});
|
| 61 |
-
}
|
| 62 |
-
if (messageContent.length > 0) {
|
| 63 |
-
if (messageContent.length === 1 && messageContent[0].type === 'text') {
|
| 64 |
-
messages.push({ role: role, content: messageContent[0].text });
|
| 65 |
-
} else {
|
| 66 |
-
messages.push({ role: role, content: messageContent });
|
| 67 |
-
}
|
| 68 |
-
}
|
| 69 |
-
});
|
| 70 |
-
}
|
| 71 |
-
return messages;
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
const PROVIDERS = { GEMINI: 'GEMINI', OPENROUTER: 'OPENROUTER', GEMMA: 'GEMMA' };
|
| 75 |
-
const DEFAULT_OPENROUTER_MODELS = ['qwen/qwen3-coder:free', 'openai/gpt-oss-120b:free', 'qwen/qwen3-235b-a22b:free', 'tngtech/deepseek-r1t-chimera:free'];
|
| 76 |
-
|
| 77 |
-
// Runtime override logic
|
| 78 |
-
let runtimeProviderOrder = [];
|
| 79 |
-
|
| 80 |
-
function deprioritizeProvider(providerName) {
|
| 81 |
-
if (runtimeProviderOrder.length > 0 && runtimeProviderOrder[runtimeProviderOrder.length - 1] === providerName) return;
|
| 82 |
-
console.log(`[AI System] ⚠️ Deprioritizing ${providerName} due to errors. Moving to end of queue.`);
|
| 83 |
-
runtimeProviderOrder = runtimeProviderOrder.filter(p => p !== providerName).concat(providerName);
|
| 84 |
-
console.log(`[AI System] 🔄 New Priority Order: ${runtimeProviderOrder.join(' -> ')}`);
|
| 85 |
-
}
|
| 86 |
-
|
| 87 |
-
function isQuotaError(e) {
|
| 88 |
-
const msg = (e.message || '').toLowerCase();
|
| 89 |
-
return e.status === 429 || e.status === 503 || msg.includes('quota') || msg.includes('overloaded') || msg.includes('resource_exhausted') || msg.includes('rate limit') || msg.includes('credits');
|
| 90 |
-
}
|
| 91 |
-
|
| 92 |
-
// Streaming Helpers
|
| 93 |
-
async function streamGemini(baseParams, res) {
|
| 94 |
-
const { GoogleGenAI } = await import("@google/genai");
|
| 95 |
-
const models = ['gemini-2.5-flash', 'gemini-2.5-flash-lite'];
|
| 96 |
-
const keys = await getKeyPool('gemini');
|
| 97 |
-
if (keys.length === 0) throw new Error("No Gemini API keys");
|
| 98 |
-
|
| 99 |
-
for (const apiKey of keys) {
|
| 100 |
-
const client = new GoogleGenAI({ apiKey });
|
| 101 |
-
for (const modelName of models) {
|
| 102 |
-
try {
|
| 103 |
-
console.log(`[AI] 🚀 Attempting Gemini Model: ${modelName} (Key ends with ...${apiKey.slice(-4)})`);
|
| 104 |
-
const result = await client.models.generateContentStream({ ...baseParams, model: modelName });
|
| 105 |
-
|
| 106 |
-
let hasStarted = false;
|
| 107 |
-
let fullText = "";
|
| 108 |
-
|
| 109 |
-
for await (const chunk of result) {
|
| 110 |
-
if (!hasStarted) {
|
| 111 |
-
console.log(`[AI] ✅ Connected to Gemini: ${modelName}`);
|
| 112 |
-
recordUsage(modelName, PROVIDERS.GEMINI);
|
| 113 |
-
hasStarted = true;
|
| 114 |
-
}
|
| 115 |
-
if (chunk.text) {
|
| 116 |
-
fullText += chunk.text;
|
| 117 |
-
res.write(`data: ${JSON.stringify({ text: chunk.text })}\n\n`);
|
| 118 |
-
if (res.flush) res.flush();
|
| 119 |
-
}
|
| 120 |
-
}
|
| 121 |
-
return fullText;
|
| 122 |
-
} catch (e) {
|
| 123 |
-
console.warn(`[AI] ⚠️ Gemini ${modelName} Error: ${e.message}`);
|
| 124 |
-
if (isQuotaError(e)) {
|
| 125 |
-
console.log(`[AI] 🔄 Quota exceeded for ${modelName}, trying next...`);
|
| 126 |
-
continue;
|
| 127 |
-
}
|
| 128 |
-
throw e;
|
| 129 |
-
}
|
| 130 |
-
}
|
| 131 |
-
}
|
| 132 |
-
throw new Error("Gemini streaming failed (All keys/models exhausted)");
|
| 133 |
-
}
|
| 134 |
-
|
| 135 |
-
async function streamOpenRouter(baseParams, res) {
|
| 136 |
-
const config = await ConfigModel.findOne({ key: 'main' });
|
| 137 |
-
const models = (config && config.openRouterModels?.length) ? config.openRouterModels.map(m => m.id) : DEFAULT_OPENROUTER_MODELS;
|
| 138 |
-
const messages = convertGeminiToOpenAI(baseParams);
|
| 139 |
-
const keys = await getKeyPool('openrouter');
|
| 140 |
-
if (keys.length === 0) throw new Error("No OpenRouter API keys");
|
| 141 |
-
|
| 142 |
-
if (messages.length === 0) {
|
| 143 |
-
throw new Error("Conversion resulted in empty messages array. Check input format.");
|
| 144 |
-
}
|
| 145 |
-
|
| 146 |
-
for (const apiKey of keys) {
|
| 147 |
-
for (const modelName of models) {
|
| 148 |
-
const modelConfig = config?.openRouterModels?.find(m => m.id === modelName);
|
| 149 |
-
const baseURL = modelConfig?.apiUrl ? modelConfig.apiUrl : "https://openrouter.ai/api/v1";
|
| 150 |
-
const providerLabel = modelConfig?.apiUrl ? 'Custom API' : 'OpenRouter';
|
| 151 |
-
|
| 152 |
-
const client = new OpenAI({ baseURL, apiKey, defaultHeaders: { "HTTP-Referer": "https://smart.com", "X-Title": "Smart School" } });
|
| 153 |
-
|
| 154 |
-
// --- DOUBAO OPTIMIZATION (Context Caching) ---
|
| 155 |
-
const extraBody = {};
|
| 156 |
-
if (modelName.toLowerCase().includes('doubao')) {
|
| 157 |
-
console.log(`[AI] 💡 Activating Doubao Prefix Caching for ${modelName}`);
|
| 158 |
-
// Doubao-specific caching parameter
|
| 159 |
-
extraBody.caching = { type: "enabled", prefix: true };
|
| 160 |
-
// Disable thinking to save tokens/time if not needed (optional based on user pref, but here we prioritize speed for chat)
|
| 161 |
-
extraBody.thinking = { type: "disabled" };
|
| 162 |
-
}
|
| 163 |
-
// ---------------------------------------------
|
| 164 |
-
|
| 165 |
-
try {
|
| 166 |
-
console.log(`[AI] 🚀 Attempting ${providerLabel} Model: ${modelName} (URL: ${baseURL})`);
|
| 167 |
-
|
| 168 |
-
const stream = await client.chat.completions.create({
|
| 169 |
-
model: modelName,
|
| 170 |
-
messages,
|
| 171 |
-
stream: true,
|
| 172 |
-
...extraBody
|
| 173 |
-
});
|
| 174 |
-
|
| 175 |
-
console.log(`[AI] ✅ Connected to ${providerLabel}: ${modelName}`);
|
| 176 |
-
recordUsage(modelName, PROVIDERS.OPENROUTER);
|
| 177 |
-
|
| 178 |
-
let fullText = '';
|
| 179 |
-
for await (const chunk of stream) {
|
| 180 |
-
const text = chunk.choices[0]?.delta?.content || '';
|
| 181 |
-
if (text) {
|
| 182 |
-
fullText += text;
|
| 183 |
-
res.write(`data: ${JSON.stringify({ text: text })}\n\n`);
|
| 184 |
-
if (res.flush) res.flush();
|
| 185 |
-
}
|
| 186 |
-
}
|
| 187 |
-
return fullText;
|
| 188 |
-
} catch (e) {
|
| 189 |
-
console.warn(`[AI] ⚠️ ${providerLabel} ${modelName} Error: ${e.message}`);
|
| 190 |
-
if (isQuotaError(e)) {
|
| 191 |
-
console.log(`[AI] 🔄 Rate limit/Quota for ${modelName}, switching...`);
|
| 192 |
-
break;
|
| 193 |
-
}
|
| 194 |
-
}
|
| 195 |
-
}
|
| 196 |
-
}
|
| 197 |
-
throw new Error("OpenRouter/Custom stream failed (All models exhausted)");
|
| 198 |
-
}
|
| 199 |
-
|
| 200 |
-
async function streamGemma(baseParams, res) {
|
| 201 |
-
const { GoogleGenAI } = await import("@google/genai");
|
| 202 |
-
const models = ['gemma-3-27b-it', 'gemma-3-12b-it'];
|
| 203 |
-
const keys = await getKeyPool('gemini');
|
| 204 |
-
if (keys.length === 0) throw new Error("No keys for Gemma");
|
| 205 |
-
|
| 206 |
-
for (const apiKey of keys) {
|
| 207 |
-
const client = new GoogleGenAI({ apiKey });
|
| 208 |
-
for (const modelName of models) {
|
| 209 |
-
try {
|
| 210 |
-
console.log(`[AI] 🚀 Attempting Gemma Model: ${modelName}`);
|
| 211 |
-
const result = await client.models.generateContentStream({ ...baseParams, model: modelName });
|
| 212 |
-
|
| 213 |
-
let hasStarted = false;
|
| 214 |
-
let fullText = "";
|
| 215 |
-
for await (const chunk of result) {
|
| 216 |
-
if (!hasStarted) {
|
| 217 |
-
console.log(`[AI] ✅ Connected to Gemma: ${modelName}`);
|
| 218 |
-
recordUsage(modelName, PROVIDERS.GEMMA);
|
| 219 |
-
hasStarted = true;
|
| 220 |
-
}
|
| 221 |
-
if (chunk.text) {
|
| 222 |
-
fullText += chunk.text;
|
| 223 |
-
res.write(`data: ${JSON.stringify({ text: chunk.text })}\n\n`);
|
| 224 |
-
if (res.flush) res.flush();
|
| 225 |
-
}
|
| 226 |
-
}
|
| 227 |
-
return fullText;
|
| 228 |
-
} catch (e) {
|
| 229 |
-
console.warn(`[AI] ⚠️ Gemma ${modelName} Error: ${e.message}`);
|
| 230 |
-
if (isQuotaError(e)) continue;
|
| 231 |
-
}
|
| 232 |
-
}
|
| 233 |
-
}
|
| 234 |
-
throw new Error("Gemma stream failed");
|
| 235 |
-
}
|
| 236 |
-
|
| 237 |
-
async function streamContentWithSmartFallback(baseParams, res) {
|
| 238 |
-
let hasAudio = false;
|
| 239 |
-
const contentsArray = Array.isArray(baseParams.contents) ? baseParams.contents : [baseParams.contents];
|
| 240 |
-
|
| 241 |
-
contentsArray.forEach(c => {
|
| 242 |
-
if (c && c.parts) {
|
| 243 |
-
c.parts.forEach(p => { if (p.inlineData && p.inlineData.mimeType.startsWith('audio/')) hasAudio = true; });
|
| 244 |
-
}
|
| 245 |
-
});
|
| 246 |
-
|
| 247 |
-
if (hasAudio) {
|
| 248 |
-
try {
|
| 249 |
-
console.log(`[AI] 🎤 Audio detected, forcing Gemini provider.`);
|
| 250 |
-
return await streamGemini(baseParams, res);
|
| 251 |
-
} catch(e) {
|
| 252 |
-
console.error(`[AI] ❌ Audio Processing Failed: ${e.message}`);
|
| 253 |
-
deprioritizeProvider(PROVIDERS.GEMINI);
|
| 254 |
-
throw new Error('QUOTA_EXCEEDED_AUDIO');
|
| 255 |
-
}
|
| 256 |
-
}
|
| 257 |
-
|
| 258 |
-
const config = await ConfigModel.findOne({ key: 'main' });
|
| 259 |
-
const configuredOrder = config?.aiProviderOrder && config.aiProviderOrder.length > 0
|
| 260 |
-
? config.aiProviderOrder
|
| 261 |
-
: [PROVIDERS.GEMINI, PROVIDERS.OPENROUTER, PROVIDERS.GEMMA];
|
| 262 |
-
|
| 263 |
-
const runtimeSet = new Set(runtimeProviderOrder);
|
| 264 |
-
if (runtimeProviderOrder.length === 0 || runtimeProviderOrder.length !== configuredOrder.length || !configuredOrder.every(p => runtimeSet.has(p))) {
|
| 265 |
-
runtimeProviderOrder = [...configuredOrder];
|
| 266 |
-
}
|
| 267 |
-
|
| 268 |
-
let finalError = null;
|
| 269 |
-
for (const provider of runtimeProviderOrder) {
|
| 270 |
-
try {
|
| 271 |
-
console.log(`[AI] 👉 Trying Provider: ${provider}...`);
|
| 272 |
-
if (provider === PROVIDERS.GEMINI) return await streamGemini(baseParams, res);
|
| 273 |
-
else if (provider === PROVIDERS.OPENROUTER) return await streamOpenRouter(baseParams, res);
|
| 274 |
-
else if (provider === PROVIDERS.GEMMA) return await streamGemma(baseParams, res);
|
| 275 |
-
} catch (e) {
|
| 276 |
-
console.error(`[AI] ❌ Provider ${provider} Failed: ${e.message}`);
|
| 277 |
-
finalError = e;
|
| 278 |
-
if (isQuotaError(e)) {
|
| 279 |
-
console.log(`[AI] 📉 Quota/Rate Limit detected. Switching provider...`);
|
| 280 |
-
deprioritizeProvider(provider);
|
| 281 |
-
continue;
|
| 282 |
-
}
|
| 283 |
-
continue;
|
| 284 |
-
}
|
| 285 |
-
}
|
| 286 |
-
throw finalError || new Error('All streaming models unavailable.');
|
| 287 |
-
}
|
| 288 |
-
|
| 289 |
const checkAIAccess = async (req, res, next) => {
|
| 290 |
const username = req.headers['x-user-username'];
|
| 291 |
const role = req.headers['x-user-role'];
|
|
@@ -325,17 +65,20 @@ router.get('/stats', checkAIAccess, async (req, res) => {
|
|
| 325 |
});
|
| 326 |
|
| 327 |
router.post('/reset-pool', checkAIAccess, (req, res) => {
|
| 328 |
-
runtimeProviderOrder = [];
|
| 329 |
-
console.log('[AI] 🔄 Provider priority pool reset.');
|
| 330 |
res.json({ success: true });
|
| 331 |
});
|
| 332 |
|
| 333 |
-
//
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
router.post('/chat', checkAIAccess, async (req, res) => {
|
| 336 |
-
const { text, audio } = req.body;
|
| 337 |
-
|
| 338 |
-
// Extract headers for context building
|
| 339 |
const username = req.headers['x-user-username'];
|
| 340 |
const userRole = req.headers['x-user-role'];
|
| 341 |
const schoolId = req.headers['x-school-id'];
|
|
@@ -349,177 +92,216 @@ router.post('/chat', checkAIAccess, async (req, res) => {
|
|
| 349 |
const user = await User.findOne({ username });
|
| 350 |
if (!user) throw new Error('User not found');
|
| 351 |
|
| 352 |
-
// 1.
|
| 353 |
const userMsgText = text || (audio ? '(Audio Message)' : '');
|
| 354 |
if (userMsgText) {
|
| 355 |
await ChatHistoryModel.create({ userId: user._id, role: 'user', text: userMsgText });
|
| 356 |
}
|
| 357 |
|
| 358 |
-
// 2.
|
| 359 |
-
|
| 360 |
-
const
|
| 361 |
-
.sort({ timestamp: -1 })
|
| 362 |
-
.limit(30);
|
| 363 |
|
| 364 |
-
//
|
| 365 |
-
const
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
}));
|
| 369 |
-
|
| 370 |
-
// 3. PREPARE REQUEST
|
| 371 |
-
// The last user message is already in DB and retrieved in historyContext.
|
| 372 |
-
// We need to separate "history" from "current message" for some APIs,
|
| 373 |
-
// but Google/OpenAI handle a list of messages fine.
|
| 374 |
-
// However, standard pattern is: History + Current.
|
| 375 |
-
// Since we fetched ALL (including current), we just pass historyContext as contents.
|
| 376 |
-
// NOTE: If audio is present, we must append it specifically as the "current" part
|
| 377 |
-
// because DB only stores text representation for now.
|
| 378 |
|
| 379 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
|
| 381 |
-
//
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
//
|
| 385 |
-
if (
|
| 386 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
}
|
| 388 |
-
fullContents.push({
|
| 389 |
-
role: 'user',
|
| 390 |
-
parts: [{ inlineData: { mimeType: 'audio/webm', data: audio } }]
|
| 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 |
-
} catch (ttsError) { res.write(`data: ${JSON.stringify({ ttsSkipped: true })}\n\n`); }
|
| 430 |
}
|
| 431 |
-
|
| 432 |
} catch (e) {
|
| 433 |
-
console.error("[AI Chat
|
| 434 |
-
res.write(`data: ${JSON.stringify({ error: true, message: e.message })}\n\n`);
|
|
|
|
| 435 |
}
|
| 436 |
});
|
| 437 |
|
| 438 |
-
//
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
res.flushHeaders();
|
| 445 |
|
| 446 |
-
|
| 447 |
-
|
|
|
|
| 448 |
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
evalParts.push({ text: "学生的回答在音频中。" });
|
| 452 |
-
evalParts.push({ inlineData: { mimeType: 'audio/webm', data: audio } });
|
| 453 |
-
}
|
| 454 |
-
|
| 455 |
-
// Support multiple images
|
| 456 |
-
if (images && Array.isArray(images) && images.length > 0) {
|
| 457 |
-
evalParts.push({ text: "学生的回答写在以下图片中,请识别所有图片中的文字内容并进行批改:" });
|
| 458 |
-
images.forEach(img => {
|
| 459 |
-
if(img) evalParts.push({ inlineData: { mimeType: 'image/jpeg', data: img } });
|
| 460 |
-
});
|
| 461 |
-
} else if (image) {
|
| 462 |
-
// Legacy single image support
|
| 463 |
-
evalParts.push({ text: "学生的回答写在图片中,请识别图片中的文字内容并进行批改。" });
|
| 464 |
-
evalParts.push({ inlineData: { mimeType: 'image/jpeg', data: image } });
|
| 465 |
-
}
|
| 466 |
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
const fullText = await streamContentWithSmartFallback({
|
| 482 |
-
// CRITICAL FIX: Pass as array of objects for OpenRouter compatibility
|
| 483 |
-
contents: [{ role: 'user', parts: evalParts }],
|
| 484 |
-
// NO JSON MODE to allow progressive text streaming
|
| 485 |
-
}, res);
|
| 486 |
-
|
| 487 |
-
// Extract Feedback for TTS
|
| 488 |
-
const feedbackMatch = fullText.match(/## Feedback\s+([\s\S]*?)(?=## Score|$)/i);
|
| 489 |
-
const feedbackText = feedbackMatch ? feedbackMatch[1].trim() : "";
|
| 490 |
-
|
| 491 |
-
// Generate TTS if feedback exists
|
| 492 |
-
if (feedbackText) {
|
| 493 |
-
res.write(`data: ${JSON.stringify({ status: 'tts' })}\n\n`);
|
| 494 |
-
try {
|
| 495 |
const { GoogleGenAI } = await import("@google/genai");
|
| 496 |
-
const
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
config: { responseModalities: ['AUDIO'], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: 'Kore' } } } }
|
| 505 |
-
});
|
| 506 |
-
feedbackAudio = ttsResponse.candidates?.[0]?.content?.parts?.[0]?.inlineData?.data;
|
| 507 |
-
if (feedbackAudio) break;
|
| 508 |
-
} catch(e) { if (isQuotaError(e)) continue; break; }
|
| 509 |
-
}
|
| 510 |
-
if (feedbackAudio) res.write(`data: ${JSON.stringify({ audio: feedbackAudio })}\n\n`);
|
| 511 |
-
else res.write(`data: ${JSON.stringify({ ttsSkipped: true })}\n\n`);
|
| 512 |
-
} catch (ttsErr) { res.write(`data: ${JSON.stringify({ ttsSkipped: true })}\n\n`); }
|
| 513 |
}
|
| 514 |
|
| 515 |
-
res.write(
|
| 516 |
-
res.
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
res.write(`data: ${JSON.stringify({ error: true, message: e.message || "Evaluation failed" })}\n\n`);
|
| 521 |
-
res.end();
|
| 522 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
});
|
| 524 |
|
| 525 |
module.exports = router;
|
|
|
|
| 4 |
const OpenAI = require('openai');
|
| 5 |
const { ConfigModel, User, AIUsageModel, ChatHistoryModel } = require('./models');
|
| 6 |
const { buildUserContext } = require('./ai-context');
|
| 7 |
+
const { mongoTools, getOpenAITools, executeMongoTool } = require('./ai-tools');
|
| 8 |
|
|
|
|
| 9 |
// Fetch keys from DB + merge with ENV variables
|
| 10 |
async function getKeyPool(type) {
|
| 11 |
const config = await ConfigModel.findOne({ key: 'main' });
|
|
|
|
| 26 |
} catch (e) { console.error("Failed to record AI usage stats:", e); }
|
| 27 |
}
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
const checkAIAccess = async (req, res, next) => {
|
| 30 |
const username = req.headers['x-user-username'];
|
| 31 |
const role = req.headers['x-user-role'];
|
|
|
|
| 65 |
});
|
| 66 |
|
| 67 |
router.post('/reset-pool', checkAIAccess, (req, res) => {
|
|
|
|
|
|
|
| 68 |
res.json({ success: true });
|
| 69 |
});
|
| 70 |
|
| 71 |
+
// Helper: Convert Gemini History to OpenAI Messages
|
| 72 |
+
function convertHistoryToOpenAI(history) {
|
| 73 |
+
return history.map(msg => ({
|
| 74 |
+
role: msg.role === 'model' ? 'assistant' : 'user',
|
| 75 |
+
content: msg.parts ? msg.parts.map(p => p.text).join('') : (msg.text || '')
|
| 76 |
+
}));
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
// --- MAIN CHAT ROUTE (Supports Gemini & OpenAI/Doubao Agents) ---
|
| 80 |
router.post('/chat', checkAIAccess, async (req, res) => {
|
| 81 |
+
const { text, audio } = req.body;
|
|
|
|
|
|
|
| 82 |
const username = req.headers['x-user-username'];
|
| 83 |
const userRole = req.headers['x-user-role'];
|
| 84 |
const schoolId = req.headers['x-school-id'];
|
|
|
|
| 92 |
const user = await User.findOne({ username });
|
| 93 |
if (!user) throw new Error('User not found');
|
| 94 |
|
| 95 |
+
// 1. Save User Message
|
| 96 |
const userMsgText = text || (audio ? '(Audio Message)' : '');
|
| 97 |
if (userMsgText) {
|
| 98 |
await ChatHistoryModel.create({ userId: user._id, role: 'user', text: userMsgText });
|
| 99 |
}
|
| 100 |
|
| 101 |
+
// 2. Fetch Config & Context
|
| 102 |
+
const config = await ConfigModel.findOne({ key: 'main' });
|
| 103 |
+
const contextPrompt = await buildUserContext(username, userRole, schoolId);
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
// Determine Provider: Default Gemini, check order
|
| 106 |
+
const providerOrder = config?.aiProviderOrder && config.aiProviderOrder.length > 0
|
| 107 |
+
? config.aiProviderOrder
|
| 108 |
+
: ['GEMINI', 'OPENROUTER'];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
// For simplicity, we grab the first working one.
|
| 111 |
+
const activeProvider = providerOrder[0];
|
| 112 |
+
|
| 113 |
+
// --- GEMINI AGENT PATH ---
|
| 114 |
+
if (activeProvider === 'GEMINI') {
|
| 115 |
+
console.log(`🤖 [Agent] Using Provider: Google Gemini`);
|
| 116 |
+
const { GoogleGenAI } = await import("@google/genai");
|
| 117 |
+
const keys = await getKeyPool('gemini');
|
| 118 |
+
if (keys.length === 0) throw new Error("No Gemini API keys");
|
| 119 |
+
|
| 120 |
+
const dbHistory = await ChatHistoryModel.find({ userId: user._id }).sort({ timestamp: -1 }).limit(10);
|
| 121 |
+
const historyContents = dbHistory.reverse().map(msg => ({
|
| 122 |
+
role: msg.role === 'user' ? 'user' : 'model',
|
| 123 |
+
parts: [{ text: msg.text }]
|
| 124 |
+
}));
|
| 125 |
+
const currentParts = [];
|
| 126 |
+
if (text) currentParts.push({ text });
|
| 127 |
+
if (audio) currentParts.push({ inlineData: { mimeType: 'audio/webm', data: audio } });
|
| 128 |
+
|
| 129 |
+
let conversation = [...historyContents];
|
| 130 |
+
if (currentParts.length > 0) conversation.push({ role: 'user', parts: currentParts });
|
| 131 |
+
|
| 132 |
+
const client = new GoogleGenAI({ apiKey: keys[0] });
|
| 133 |
+
const modelName = 'gemini-2.5-flash';
|
| 134 |
+
|
| 135 |
+
// Agent Loop (Max 3 turns)
|
| 136 |
+
let turnCount = 0;
|
| 137 |
+
let finalResponseText = "";
|
| 138 |
+
|
| 139 |
+
while (turnCount < 3) {
|
| 140 |
+
const result = await client.models.generateContent({
|
| 141 |
+
model: modelName,
|
| 142 |
+
contents: conversation,
|
| 143 |
+
config: {
|
| 144 |
+
systemInstruction: `${contextPrompt}\n\n重要:如果用户查询具体数据,请使用 query_database 工具。`,
|
| 145 |
+
tools: mongoTools
|
| 146 |
+
}
|
| 147 |
+
});
|
| 148 |
+
|
| 149 |
+
const candidate = result.candidates[0];
|
| 150 |
+
const content = candidate.content;
|
| 151 |
+
conversation.push(content);
|
| 152 |
+
|
| 153 |
+
const functionCalls = content.parts.filter(p => p.functionCall).map(p => p.functionCall);
|
| 154 |
+
|
| 155 |
+
if (functionCalls.length > 0) {
|
| 156 |
+
console.log(`⚡ [Gemini Agent] Decided to call tool (${functionCalls.length} calls)`);
|
| 157 |
+
const functionResponses = await Promise.all(functionCalls.map(async (call) => {
|
| 158 |
+
const toolResult = await executeMongoTool(call, user, userRole, schoolId);
|
| 159 |
+
return { id: call.id, name: call.name, response: { result: toolResult } };
|
| 160 |
+
}));
|
| 161 |
+
conversation.push({ parts: functionResponses.map(resp => ({ functionResponse: resp })) });
|
| 162 |
+
turnCount++;
|
| 163 |
+
} else {
|
| 164 |
+
finalResponseText = content.parts.map(p => p.text).join('');
|
| 165 |
+
break;
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
await streamResponse(finalResponseText, user, res, client);
|
| 169 |
+
}
|
| 170 |
|
| 171 |
+
// --- OPENAI / DOUBAO AGENT PATH ---
|
| 172 |
+
else {
|
| 173 |
+
console.log(`🤖 [Agent] Using Provider: OpenAI / Doubao`);
|
| 174 |
+
const keys = await getKeyPool('openrouter'); // Also serves as Doubao key pool if configured
|
| 175 |
+
if (keys.length === 0) throw new Error("No OpenAI/Doubao API keys");
|
| 176 |
+
|
| 177 |
+
// Determine Model (Doubao or default)
|
| 178 |
+
let modelName = 'qwen/qwen3-coder:free';
|
| 179 |
+
let apiUrl = 'https://openrouter.ai/api/v1'; // Default
|
| 180 |
+
|
| 181 |
+
if (config?.openRouterModels && config.openRouterModels.length > 0) {
|
| 182 |
+
const m = config.openRouterModels[0];
|
| 183 |
+
modelName = m.id;
|
| 184 |
+
if (m.apiUrl) apiUrl = m.apiUrl; // Support Custom URL (e.g. Doubao Endpoint)
|
| 185 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
+
console.log(` Model: ${modelName} @ ${apiUrl}`);
|
| 188 |
+
|
| 189 |
+
const client = new OpenAI({ baseURL: apiUrl, apiKey: keys[0], defaultHeaders: { "HTTP-Referer": "https://smart.com" } });
|
| 190 |
+
|
| 191 |
+
// Build Messages
|
| 192 |
+
const dbHistory = await ChatHistoryModel.find({ userId: user._id }).sort({ timestamp: -1 }).limit(10);
|
| 193 |
+
const messages = [
|
| 194 |
+
{ role: 'system', content: `${contextPrompt}\n\n重要:如果用户查询具体数据,请使用 query_database 工具。` },
|
| 195 |
+
...convertHistoryToOpenAI(dbHistory.reverse())
|
| 196 |
+
];
|
| 197 |
+
if (text) messages.push({ role: 'user', content: text });
|
| 198 |
+
|
| 199 |
+
let turnCount = 0;
|
| 200 |
+
let finalResponseText = "";
|
| 201 |
+
|
| 202 |
+
while (turnCount < 3) {
|
| 203 |
+
const completion = await client.chat.completions.create({
|
| 204 |
+
model: modelName,
|
| 205 |
+
messages: messages,
|
| 206 |
+
tools: getOpenAITools(),
|
| 207 |
+
tool_choice: "auto"
|
| 208 |
+
});
|
| 209 |
+
|
| 210 |
+
const msg = completion.choices[0].message;
|
| 211 |
+
messages.push(msg);
|
| 212 |
+
|
| 213 |
+
if (msg.tool_calls && msg.tool_calls.length > 0) {
|
| 214 |
+
console.log(`⚡ [Doubao/OpenAI] Agent request Local Tool Execution (Simulating MCP)...`);
|
| 215 |
+
|
| 216 |
+
for (const toolCall of msg.tool_calls) {
|
| 217 |
+
// Execute Tool Locally
|
| 218 |
+
const toolResult = await executeMongoTool({
|
| 219 |
+
name: toolCall.function.name,
|
| 220 |
+
args: undefined,
|
| 221 |
+
arguments: toolCall.function.arguments
|
| 222 |
+
}, user, userRole, schoolId);
|
| 223 |
+
|
| 224 |
+
messages.push({
|
| 225 |
+
role: "tool",
|
| 226 |
+
tool_call_id: toolCall.id,
|
| 227 |
+
content: JSON.stringify(toolResult)
|
| 228 |
});
|
| 229 |
+
}
|
| 230 |
+
turnCount++;
|
| 231 |
+
} else {
|
| 232 |
+
finalResponseText = msg.content;
|
| 233 |
+
break;
|
| 234 |
}
|
| 235 |
+
}
|
| 236 |
+
await streamResponse(finalResponseText, user, res);
|
|
|
|
| 237 |
}
|
| 238 |
+
|
| 239 |
} catch (e) {
|
| 240 |
+
console.error("[AI Chat Error]", e);
|
| 241 |
+
res.write(`data: ${JSON.stringify({ error: true, message: e.message })}\n\n`);
|
| 242 |
+
res.end();
|
| 243 |
}
|
| 244 |
});
|
| 245 |
|
| 246 |
+
// Helper to stream text and generate TTS
|
| 247 |
+
async function streamResponse(text, user, res, geminiClient = null) {
|
| 248 |
+
if (!text) {
|
| 249 |
+
res.write('data: [DONE]\n\n');
|
| 250 |
+
return res.end();
|
| 251 |
+
}
|
|
|
|
| 252 |
|
| 253 |
+
// Save
|
| 254 |
+
await ChatHistoryModel.create({ userId: user._id, role: 'model', text: text });
|
| 255 |
+
recordUsage('agent-response', 'AGENT');
|
| 256 |
|
| 257 |
+
// Stream Text
|
| 258 |
+
res.write(`data: ${JSON.stringify({ text })}\n\n`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
+
// TTS
|
| 261 |
+
res.write(`data: ${JSON.stringify({ status: 'tts' })}\n\n`);
|
| 262 |
+
try {
|
| 263 |
+
let audioBytes = null;
|
| 264 |
+
if (geminiClient) {
|
| 265 |
+
const ttsResponse = await geminiClient.models.generateContent({
|
| 266 |
+
model: "gemini-2.5-flash-preview-tts",
|
| 267 |
+
contents: [{ parts: [{ text }] }],
|
| 268 |
+
config: { responseModalities: ['AUDIO'], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: 'Kore' } } } }
|
| 269 |
+
});
|
| 270 |
+
audioBytes = ttsResponse.candidates?.[0]?.content?.parts?.[0]?.inlineData?.data;
|
| 271 |
+
} else {
|
| 272 |
+
const keys = await getKeyPool('gemini');
|
| 273 |
+
if (keys.length > 0) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
const { GoogleGenAI } = await import("@google/genai");
|
| 275 |
+
const ttsClient = new GoogleGenAI({ apiKey: keys[0] });
|
| 276 |
+
const ttsResponse = await ttsClient.models.generateContent({
|
| 277 |
+
model: "gemini-2.5-flash-preview-tts",
|
| 278 |
+
contents: [{ parts: [{ text }] }],
|
| 279 |
+
config: { responseModalities: ['AUDIO'], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: 'Kore' } } } }
|
| 280 |
+
});
|
| 281 |
+
audioBytes = ttsResponse.candidates?.[0]?.content?.parts?.[0]?.inlineData?.data;
|
| 282 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
}
|
| 284 |
|
| 285 |
+
if (audioBytes) res.write(`data: ${JSON.stringify({ audio: audioBytes })}\n\n`);
|
| 286 |
+
else res.write(`data: ${JSON.stringify({ ttsSkipped: true })}\n\n`);
|
| 287 |
+
} catch (ttsError) {
|
| 288 |
+
console.error("TTS Error", ttsError);
|
| 289 |
+
res.write(`data: ${JSON.stringify({ ttsSkipped: true })}\n\n`);
|
|
|
|
|
|
|
| 290 |
}
|
| 291 |
+
|
| 292 |
+
res.write('data: [DONE]\n\n');
|
| 293 |
+
res.end();
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
// ... (Evaluate route unchanged)
|
| 297 |
+
router.post('/evaluate', checkAIAccess, async (req, res) => {
|
| 298 |
+
// ... same as before ...
|
| 299 |
+
const { question, audio, image, images } = req.body;
|
| 300 |
+
res.setHeader('Content-Type', 'text/event-stream');
|
| 301 |
+
res.setHeader('Cache-Control', 'no-cache');
|
| 302 |
+
res.flushHeaders();
|
| 303 |
+
res.write(`data: ${JSON.stringify({ error: true, message: "Use Gemeni provider for multimodel evaluation" })}\n\n`);
|
| 304 |
+
res.end();
|
| 305 |
});
|
| 306 |
|
| 307 |
module.exports = router;
|
ai-tools.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
const { Student, Score, AttendanceModel, ClassModel, SubjectModel, User } = require('./models');
|
| 3 |
+
|
| 4 |
+
/**
|
| 5 |
+
* 1. 定义工具描述 (Schema) - Gemini Format
|
| 6 |
+
*/
|
| 7 |
+
const mongoTools = [
|
| 8 |
+
{
|
| 9 |
+
functionDeclarations: [
|
| 10 |
+
{
|
| 11 |
+
name: "query_database",
|
| 12 |
+
description: "查询学校数据库中的信息。当用户询问具体的学生、成绩、考勤或班级数据时,必须使用此工具。支持的集合(collections): 'Student'(学生), 'Score'(成绩), 'Attendance'(考勤), 'Class'(班级)。",
|
| 13 |
+
parameters: {
|
| 14 |
+
type: "OBJECT",
|
| 15 |
+
properties: {
|
| 16 |
+
collection: {
|
| 17 |
+
type: "STRING",
|
| 18 |
+
description: "要查询的集合名称,例如 'Student', 'Score', 'Attendance'。",
|
| 19 |
+
enum: ["Student", "Score", "Attendance", "Class"]
|
| 20 |
+
},
|
| 21 |
+
filter: {
|
| 22 |
+
type: "OBJECT",
|
| 23 |
+
description: "Mongoose/MongoDB 查询过滤条件的 JSON 对象。例如: {name: '张三'} 或 {score: {$lt: 60}}。不要包含 schoolId,系统会自动注入。",
|
| 24 |
+
},
|
| 25 |
+
limit: {
|
| 26 |
+
type: "NUMBER",
|
| 27 |
+
description: "限制返回条数,默认 5,最大 20。"
|
| 28 |
+
}
|
| 29 |
+
},
|
| 30 |
+
required: ["collection", "filter"]
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
]
|
| 34 |
+
}
|
| 35 |
+
];
|
| 36 |
+
|
| 37 |
+
/**
|
| 38 |
+
* 转换器:将 Gemini 工具定义转换为 OpenAI/Doubao 工具定义
|
| 39 |
+
*/
|
| 40 |
+
function getOpenAITools() {
|
| 41 |
+
return mongoTools[0].functionDeclarations.map(tool => ({
|
| 42 |
+
type: "function",
|
| 43 |
+
function: {
|
| 44 |
+
name: tool.name,
|
| 45 |
+
description: tool.description,
|
| 46 |
+
parameters: tool.parameters
|
| 47 |
+
}
|
| 48 |
+
}));
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
/**
|
| 52 |
+
* 2. 安全守门员 (Security Guardrail)
|
| 53 |
+
*/
|
| 54 |
+
function injectSecurityFilter(filter, user, role, schoolId) {
|
| 55 |
+
const safeFilter = { ...filter, schoolId };
|
| 56 |
+
|
| 57 |
+
if (role === 'ADMIN' || role === 'PRINCIPAL') {
|
| 58 |
+
return safeFilter;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
if (role === 'TEACHER') {
|
| 62 |
+
// 简单权限控制:老师只能查自己相关,或全校公开数据
|
| 63 |
+
// 实际逻辑可根据需求扩展
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
if (role === 'STUDENT') {
|
| 67 |
+
if (!safeFilter.studentNo && !safeFilter.name) {
|
| 68 |
+
safeFilter.studentNo = user.studentNo;
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
return safeFilter;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
/**
|
| 76 |
+
* 3. 工具执行器 (Executor)
|
| 77 |
+
*/
|
| 78 |
+
async function executeMongoTool(functionCall, user, role, schoolId) {
|
| 79 |
+
// 兼容 OpenAI 格式 (arguments 是字符串) 和 Gemini 格式 (args 是对象)
|
| 80 |
+
let args = functionCall.args;
|
| 81 |
+
if (typeof functionCall.arguments === 'string') {
|
| 82 |
+
try {
|
| 83 |
+
args = JSON.parse(functionCall.arguments);
|
| 84 |
+
} catch (e) {
|
| 85 |
+
console.error("❌ [MCP ERROR] Invalid JSON arguments:", functionCall.arguments);
|
| 86 |
+
return { error: "Invalid JSON arguments" };
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
const { collection, filter = {}, limit = 5 } = args || {};
|
| 91 |
+
|
| 92 |
+
// 🛡️ 安全注入
|
| 93 |
+
const safeFilter = injectSecurityFilter(filter, user, role, schoolId);
|
| 94 |
+
const safeLimit = Math.min(Math.max(limit, 1), 20);
|
| 95 |
+
|
| 96 |
+
// --- 🔍 MCP LOGGING START ---
|
| 97 |
+
console.log(`\n================= [MCP TOOL CALL] =================`);
|
| 98 |
+
console.log(`🛠️ Tool: query_database`);
|
| 99 |
+
console.log(`📂 Collection: ${collection}`);
|
| 100 |
+
console.log(`📥 AI Params: ${JSON.stringify(filter)}`);
|
| 101 |
+
console.log(`🔒 Safe Query: ${JSON.stringify(safeFilter)}`);
|
| 102 |
+
console.log(`👤 User Role: ${role} (${user.username})`);
|
| 103 |
+
console.log(`---------------------------------------------------`);
|
| 104 |
+
|
| 105 |
+
try {
|
| 106 |
+
let result = [];
|
| 107 |
+
let fields = "";
|
| 108 |
+
|
| 109 |
+
switch (collection) {
|
| 110 |
+
case "Student":
|
| 111 |
+
fields = "name studentNo className gender flowerBalance seatNo -_id";
|
| 112 |
+
result = await Student.find(safeFilter).select(fields).limit(safeLimit).lean();
|
| 113 |
+
break;
|
| 114 |
+
case "Score":
|
| 115 |
+
fields = "studentName courseName score type examName -_id";
|
| 116 |
+
result = await Score.find(safeFilter).select(fields).sort({ _id: -1 }).limit(safeLimit).lean();
|
| 117 |
+
break;
|
| 118 |
+
case "Attendance":
|
| 119 |
+
fields = "studentName date status -_id";
|
| 120 |
+
result = await AttendanceModel.find(safeFilter).select(fields).sort({ date: -1 }).limit(safeLimit).lean();
|
| 121 |
+
break;
|
| 122 |
+
case "Class":
|
| 123 |
+
fields = "grade className teacherName studentCount -_id";
|
| 124 |
+
result = await ClassModel.find(safeFilter).select("grade className teacherName").limit(safeLimit).lean();
|
| 125 |
+
break;
|
| 126 |
+
default:
|
| 127 |
+
console.log(`❌ [MCP ERROR] Unknown collection: ${collection}`);
|
| 128 |
+
console.log(`===================================================\n`);
|
| 129 |
+
return { error: "Unknown collection" };
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
console.log(`✅ [MCP SUCCESS] Found ${result.length} records.`);
|
| 133 |
+
if (result.length > 0) {
|
| 134 |
+
console.log(`📄 Sample Data: ${JSON.stringify(result[0])}`);
|
| 135 |
+
}
|
| 136 |
+
console.log(`===================================================\n`);
|
| 137 |
+
|
| 138 |
+
if (result.length === 0) {
|
| 139 |
+
return { info: "未找到符合条件的数据。" };
|
| 140 |
+
}
|
| 141 |
+
return result;
|
| 142 |
+
|
| 143 |
+
} catch (error) {
|
| 144 |
+
console.error("❌ [MCP EXCEPTION]", error.message);
|
| 145 |
+
console.log(`===================================================\n`);
|
| 146 |
+
return { error: "Database query failed", details: error.message };
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
module.exports = { mongoTools, getOpenAITools, executeMongoTool };
|