/** * 假的 OpenAI 兼容服务 + 假的火山语音服务,用来端到端验证内核(不消耗任何真实额度)。 * * 对话:第一轮返回 tool_call(calc),第二轮根据工具结果流式回答。 * 语音:/v1/audio/speech 回一段真 WAV;/v1/audio/transcriptions 回固定文字; * 还顺手把收到的请求形状打出来,用来核对"我们到底发了什么头/字段"。 */ import http from 'node:http'; const PORT = Number(process.env.MOCK_PORT || 5299); /** * 回复长度(字符数)。默认是原来那段短回答。 * * 为什么做成可配:有一类 bug **只有长内容才暴露** —— 比如朗读播到一半被砍 * (收尾死线写死 15 秒,而一段 210 字的回答有 38.8 秒音频)。 * 拿短回复测永远是绿的,必须能造出长回复。 * * MOCK_REPLY_CHARS=400 node scripts/mock-llm.mjs */ const REPLY_CHARS = Number(process.env.MOCK_REPLY_CHARS || 0); /** 造一段指定字数的中文回复 */ function longReply(chars) { const unit = '人工智能正在改变我们生活的方方面面,从早上叫醒我们的智能音箱,' + '到通勤路上推荐路线的导航软件,再到工作中帮我们整理资料的助手。'; let out = ''; while (out.length < chars) out += unit; return out.slice(0, chars); } function sse(res, obj) { res.write(`data: ${JSON.stringify(obj)}\n\n`); } /** 造一段 0.3 秒的正弦波 WAV(16000Hz 单声道 16bit),用来验证播放链路 */ function makeWav(seconds = 0.3, freq = 440) { const rate = 16000; const n = Math.floor(rate * seconds); const data = Buffer.alloc(n * 2); for (let i = 0; i < n; i += 1) { data.writeInt16LE(Math.round(Math.sin((2 * Math.PI * freq * i) / rate) * 8000), i * 2); } const header = Buffer.alloc(44); header.write('RIFF', 0); header.writeUInt32LE(36 + data.length, 4); header.write('WAVE', 8); header.write('fmt ', 12); header.writeUInt32LE(16, 16); header.writeUInt16LE(1, 20); header.writeUInt16LE(1, 22); header.writeUInt32LE(rate, 24); header.writeUInt32LE(rate * 2, 28); header.writeUInt16LE(2, 32); header.writeUInt16LE(16, 34); header.write('data', 36); header.writeUInt32LE(data.length, 40); return Buffer.concat([header, data]); } const server = http.createServer(async (req, res) => { const url = req.url || ''; /* ---------------- 语音合成(OpenAI 兼容 /audio/speech)---------------- */ if (url.startsWith('/v1/audio/speech')) { const chunks = []; for await (const c of req) chunks.push(c); let body = {}; try { body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); } catch { /* 下面照常回音频 */ } console.log( `[mock][tts] auth=${req.headers.authorization ? '有' : '无'} model=${body.model} ` + `voice=${body.voice} speed=${body.speed} fmt=${body.response_format} ` + `文本=${JSON.stringify(String(body.input || '').slice(0, 30))}`, ); const wav = makeWav(0.3, 520); res.writeHead(200, { 'Content-Type': 'audio/wav', 'Content-Length': wav.length }).end(wav); return; } /* ---------------- 语音合成(火山 v1 /api/v1/tts)---------------- */ if (url.startsWith('/api/v1/tts')) { const chunks = []; for await (const c of req) chunks.push(c); let body = {}; try { body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); } catch { /* 忽略 */ } const auth = req.headers.authorization || ''; console.log( `[mock][volc-tts] Authorization=${JSON.stringify(auth)} ` + `app.appid=${body.app?.appid} app.token=${body.app?.token ? '有' : '无'} app.cluster=${body.app?.cluster} ` + `audio.voice_type=${body.audio?.voice_type} audio.encoding=${body.audio?.encoding} ` + `audio.speed_ratio=${body.audio?.speed_ratio} ` + `request.text_type=${body.request?.text_type} request.operation=${body.request?.operation} ` + `request.reqid=${body.request?.reqid ? '有' : '无'} text=${JSON.stringify(String(body.request?.text || '').slice(0, 20))}`, ); // 校验鉴权头是不是文档要求的分号形式 —— 这正是最容易写错的地方 const semicolonOk = auth.startsWith('Bearer;'); if (!semicolonOk) { res.writeHead(200, { 'Content-Type': 'application/json' }).end( JSON.stringify({ code: 3001, message: '鉴权头格式不对:必须是 Bearer;(分号)' }), ); return; } const wav = makeWav(0.3, 660); res.writeHead(200, { 'Content-Type': 'application/json' }).end( JSON.stringify({ code: 3000, message: 'Success', reqid: body.request?.reqid, data: wav.toString('base64') }), ); return; } /* ---------------- 语音识别(OpenAI 兼容 /audio/transcriptions)---------------- */ if (url.startsWith('/v1/audio/transcriptions')) { const chunks = []; for await (const c of req) chunks.push(c); const raw = Buffer.concat(chunks); const ctype = req.headers['content-type'] || ''; const boundary = (ctype.match(/boundary=(.+)$/) || [])[1] || ''; const text = raw.toString('latin1'); const model = (text.match(/name="model"\r\n\r\n([^\r]*)/) || [])[1] || '?'; const hasFile = text.includes('name="file"') && text.includes('filename='); console.log( `[mock][stt] auth=${req.headers.authorization ? '有' : '无'} boundary=${boundary ? '有' : '无'} ` + `model=${model} 带文件=${hasFile} 体积=${raw.length}`, ); res.writeHead(200, { 'Content-Type': 'application/json' }).end( JSON.stringify({ text: '这是语音识别的模拟结果' }), ); return; } if (!url.startsWith('/v1/chat/completions')) { res.writeHead(404).end('nope'); return; } const chunks = []; for await (const c of req) chunks.push(c); // 别让一条坏请求把整个 mock 打死:壳脚本/手敲 curl 很容易发出不合法 JSON, // 之前没防这一下,mock 直接退出,界面那边只看到 "Remote end closed connection"。 let body; try { body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); } catch (e) { console.log('[mock] 请求体不是合法 JSON,已忽略:', e.message); res.writeHead(400, { 'Content-Type': 'application/json' }).end('{"error":"bad json"}'); return; } const messages = body.messages || []; const toolMsg = messages.findLast?.((m) => m.role === 'tool'); const hasTools = Array.isArray(body.tools) && body.tools.length > 0; console.log( `[mock] model=${body.model} tools=${body.tools?.length || 0} msgs=${messages.length} ` + `temperature=${body.temperature} thinking=${JSON.stringify(body.thinking)} ` + `reasoning_effort=${body.reasoning_effort}`, ); res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache, no-transform', Connection: 'keep-alive', }); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); if (!toolMsg && hasTools) { // 第一轮:要求调用 calc 工具 const args = JSON.stringify({ expression: '(1+2)*3' }); sse(res, { choices: [{ delta: { tool_calls: [{ index: 0, id: 'call_mock_1', type: 'function', function: { name: 'calc', arguments: args }, }], }, }], }); await sleep(120); sse(res, { choices: [{ delta: {}, finish_reason: 'tool_calls' }] }); res.write('data: [DONE]\n\n'); res.end(); return; } // 第二轮:先吐一段思维链(reasoning_content),再给最终回答 const thinking = [ '用户要算 (1+2)*3。', '我需要先调用计算工具,避免自己算错。', '工具返回的表达式是 (1+2)*3,结果是 9。', '把结果解释给用户,并说明这条链路是端到端跑通的。', ].join(''); for (const ch of thinking) { sse(res, { choices: [{ delta: { reasoning_content: ch } }] }); await sleep(8); } const toolText = toolMsg ? String(toolMsg.content) : '(没拿到工具结果)'; const answer = REPLY_CHARS > 0 ? longReply(REPLY_CHARS) : `我用 calc 工具算了一下:${toolText}\n\n所以 (1+2)*3 = 9。这条回答是端到端跑通的:界面 → 内核 → 工具调用 → 流式返回。`; for (const ch of answer) { sse(res, { choices: [{ delta: { content: ch } }] }); await sleep(12); } sse(res, { choices: [{ delta: {}, finish_reason: 'stop' }] }); sse(res, { usage: { prompt_tokens: 100, completion_tokens: 60, total_tokens: 160 }, choices: [] }); res.write('data: [DONE]\n\n'); res.end(); }); server.listen(PORT, '127.0.0.1', () => console.log(`[mock] listening on http://127.0.0.1:${PORT}/v1`));