-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
306 lines (274 loc) · 10.3 KB
/
Copy pathserver.js
File metadata and controls
306 lines (274 loc) · 10.3 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
import express from 'express';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = Number(process.env.API_PORT || 3002);
const MODEL_SERVER_URL = (process.env.MODEL_SERVER_URL || 'http://127.0.0.1:8000').replace(/\/+$/, '');
const MODEL_NAME = process.env.MODEL_NAME || 'gpt-4o-mini';
const MODEL_SERVER_API_KEY = process.env.MODEL_SERVER_API_KEY || '';
const VIDEO_MODEL_URL = process.env.VIDEO_MODEL_URL || `${MODEL_SERVER_URL}/v1/video/generate`;
const VIDEO_MODEL_API_KEY = process.env.VIDEO_MODEL_API_KEY || MODEL_SERVER_API_KEY;
const ADMIN_TOKEN = process.env.ADMIN_TOKEN || 'dev-admin-token';
const DAILY_REVENUE_CHY = Number(process.env.DAILY_REVENUE_CHY || 20000);
const DAILY_COIN_OUTPUT = Number(process.env.DAILY_COIN_OUTPUT || 3500000);
const REWARD_CONFIG = {
targetRate: 0.00012,
minRate: 0.00008,
maxRate: 0.00020,
payoutRatio: 0.06,
};
function calculateDailyBudgetCHY(dailyRevenueCHY) {
return Math.max(120, Math.round(dailyRevenueCHY * REWARD_CONFIG.payoutRatio));
}
function calculateDailyCoinQuota(dailyBudgetCHY) {
return Math.max(100000, Math.floor(dailyBudgetCHY / REWARD_CONFIG.targetRate));
}
function calculateTodayRate(dailyBudgetCHY, dailyCoinOutput) {
if (dailyCoinOutput <= 0) {
return REWARD_CONFIG.targetRate;
}
const rate = dailyBudgetCHY / Math.max(dailyCoinOutput, 1);
return Math.min(REWARD_CONFIG.maxRate, Math.max(REWARD_CONFIG.minRate, rate));
}
app.use(express.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
next();
});
const fallbackQuestions = {
数学: {
id: 'fallback-math-1',
subject: '数学',
title: '已知直角三角形的两条直角边长度分别为 6cm 和 8cm,则斜边长度为多少?',
options: [
{ label: 'A', text: '10cm' },
{ label: 'B', text: '12cm' },
{ label: 'C', text: '14cm' },
{ label: 'D', text: '15cm' }
],
correctAnswer: 'A',
analysis: [
'本题考查勾股定理:a² + b² = c²。',
'6² + 8² = 36 + 64 = 100。',
'c = √100 = 10,因此答案是 10cm。'
]
},
语文: {
id: 'fallback-chinese-1',
subject: '语文',
title: '下面哪一句诗句出自《静夜思》?',
options: [
{ label: 'A', text: '床前明月光' },
{ label: 'B', text: '停车坐爱枫林晚' },
{ label: 'C', text: '举头望明月' },
{ label: 'D', text: '无边落木萧萧下' }
],
correctAnswer: 'A',
analysis: [
'《静夜思》是李白的作品,第一句为“床前明月光”,这是本题的正确答案。',
'其他选项分别来自不同诗词,不属于《静夜思》。'
]
},
英语: {
id: 'fallback-english-1',
subject: '英语',
title: 'Which sentence is grammatically correct?',
options: [
{ label: 'A', text: 'He go to school every day.' },
{ label: 'B', text: 'He goes to school every day.' },
{ label: 'C', text: 'He going to school every day.' },
{ label: 'D', text: 'He gone to school every day.' }
],
correctAnswer: 'B',
analysis: [
'主语 He 为第三人称单数,动词 go 需要加 s,正确形式为 goes。',
'因此句子 “He goes to school every day.” 是正确的。'
]
}
};
function cleanJsonString(text) {
const match = text.match(/\{[\s\S]*\}/);
if (!match) {
return text;
}
return match[0];
}
function parseModelResponse(text) {
const payload = cleanJsonString(text.trim());
return JSON.parse(payload);
}
function validateQuestion(question) {
if (!question || !question.id || !question.title || !Array.isArray(question.options) || !question.correctAnswer) {
throw new Error('Invalid question payload received from model');
}
return question;
}
function extractVideoUrl(result) {
if (!result) return undefined;
const candidates = [
result.videoUrl,
result.url,
result.uri,
result.video?.url,
result.video?.uri,
result.data?.[0]?.url,
result.data?.[0]?.uri,
result.output?.[0]?.url,
result.output?.[0]?.uri,
result.outputs?.[0]?.url,
result.outputs?.[0]?.uri,
result.result?.videoUrl,
result.result?.url,
result.result?.uri,
];
return candidates.find((value) => typeof value === 'string' && value.length > 0);
}
async function generateVideoScript(topic) {
const endpoint = `${MODEL_SERVER_URL}/v1/chat/completions`;
const prompt = `请为知识点“${topic}”生成一个简洁明了的中文教学讲解脚本,适合制作 1 分钟左右的知识点讲解短视频。返回文本内容即可。`;
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(MODEL_SERVER_API_KEY ? { Authorization: `Bearer ${MODEL_SERVER_API_KEY}` } : {}),
},
body: JSON.stringify({
model: MODEL_NAME,
messages: [
{ role: 'system', content: '你是一个教育内容生成助手,负责写出适合视频解说的教学脚本。' },
{ role: 'user', content: prompt }
],
temperature: 0.35,
max_tokens: 300,
}),
});
if (!response.ok) {
throw new Error(`Script model returned ${response.status}`);
}
const result = await response.json();
return result?.choices?.[0]?.message?.content?.trim() || '';
}
async function generateQuestion(grade, subject) {
const prompt = `请生成一道高质量的${grade}${subject}选择题,要求输出为纯 JSON 格式,包含字段:id、grade、subject、title、options、correctAnswer、analysis。options 为数组,每个元素包含 label 和 text;analysis 为字符串数组;correctAnswer 用 ABCD 表示。不要输出额外的解释文字。`;
const endpoint = `${MODEL_SERVER_URL}/v1/chat/completions`;
const headers = {
'Content-Type': 'application/json',
};
if (MODEL_SERVER_API_KEY) {
headers.Authorization = `Bearer ${MODEL_SERVER_API_KEY}`;
}
const response = await fetch(endpoint, {
method: 'POST',
headers,
body: JSON.stringify({
model: MODEL_NAME,
messages: [
{ role: 'system', content: '你是一个高质量习题生成器。' },
{ role: 'user', content: prompt }
],
temperature: 0.1,
max_tokens: 500,
}),
});
if (!response.ok) {
throw new Error(`Model server returned ${response.status}`);
}
const result = await response.json();
const text = result?.choices?.[0]?.message?.content || result?.result || JSON.stringify(result);
const question = parseModelResponse(text);
return validateQuestion(question);
}
app.get('/api/question', async (req, res) => {
const requestedGrade = String(req.query.grade || '初中');
const requestedSubject = String(req.query.subject || '数学');
try {
const question = await generateQuestion(requestedGrade, requestedSubject);
return res.json(question);
} catch (error) {
console.error('[server] model fetch failed:', error?.message || error);
const fallback = fallbackQuestions[requestedSubject] || fallbackQuestions['数学'];
return res.json(fallback);
}
});
app.get('/api/video', async (req, res) => {
const topic = String(req.query.topic || '核心知识点讲解');
const fallbackUrl = 'https://storage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4';
const payload = {
videoUrl: fallbackUrl,
script: `正在准备“${topic}”的教学讲解短视频。`,
fallback: true,
};
try {
const script = await generateVideoScript(topic);
if (script) {
payload.script = script;
}
} catch (error) {
console.warn('[server] video script generation fallback:', error?.message || error);
}
if (VIDEO_MODEL_URL) {
try {
const response = await fetch(VIDEO_MODEL_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(VIDEO_MODEL_API_KEY ? { Authorization: `Bearer ${VIDEO_MODEL_API_KEY}` } : {}),
},
body: JSON.stringify({
topic,
prompt: `请为知识点“${topic}”生成一个简短的教学视频,并返回 JSON 格式,至少包含 videoUrl 字段。`,
}),
});
if (response.ok) {
const result = await response.json();
const videoUrl = extractVideoUrl(result);
if (videoUrl) {
payload.videoUrl = videoUrl;
payload.fallback = false;
} else {
console.warn('[server] video model responded without valid URL, using fallback');
}
} else {
console.warn('[server] video generation model returned status', response.status);
}
} catch (error) {
console.warn('[server] video generation failed, using fallback video:', error?.message || error);
}
} else {
console.warn('[server] VIDEO_MODEL_URL not configured, using fallback video');
}
return res.json(payload);
});
app.get('/api/admin/stats', (req, res) => {
const token = String(req.headers['x-admin-token'] || '');
if (token !== ADMIN_TOKEN) {
return res.status(403).json({ error: 'Forbidden: invalid admin token' });
}
const dailyBudgetCHY = calculateDailyBudgetCHY(DAILY_REVENUE_CHY);
const dailyCoinQuota = calculateDailyCoinQuota(dailyBudgetCHY);
const todayRate = calculateTodayRate(dailyBudgetCHY, DAILY_COIN_OUTPUT);
return res.json({
environment: {
apiPort: PORT,
modelServerUrl: MODEL_SERVER_URL,
modelName: MODEL_NAME,
},
rewardMonitor: {
adminTokenHint: 'X-Admin-Token header required',
dailyRevenueCHY: DAILY_REVENUE_CHY,
dailyBudgetCHY,
dailyCoinOutput: DAILY_COIN_OUTPUT,
dailyCoinQuota,
todayRate,
rewardConfig: REWARD_CONFIG,
},
timestamp: new Date().toISOString(),
});
});
app.listen(PORT, () => {
console.log(`AI model proxy server is running at http://127.0.0.1:${PORT}`);
console.log(`Using model gateway: ${MODEL_SERVER_URL}`);
console.log(`Admin stats endpoint available at http://127.0.0.1:${PORT}/api/admin/stats`);
});