136 lines
8.0 KiB
JavaScript
Executable File
136 lines
8.0 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
||
// 驗證用的假模型:OpenAI 相容的 /v1/chat/completions,回固定答案,不連任何真的模型服務。
|
||
// AnyBot 的「自訂(OpenAI 相容)」供應商指到這裡(ctl up 用 `setup --seed` 設好)。
|
||
//
|
||
// 規則(只看最後一則訊息,所以不會無限迴圈):
|
||
// - 最後一則是工具結果 → 文字「FAKE-MODEL 收到工具結果:…」,這一輪結束。
|
||
// - 使用者訊息裡有 [[call 工具 {JSON}]] → 叫那個工具(這一輪的工具清單裡要有)。
|
||
// - 其他 → 文字「FAKE-MODEL 回答:<使用者那句>」。
|
||
// - 沒帶工具的請求(AnyBot 自己的小工作:摘要、記憶、標題…)→ 文字「FAKE-MODEL 輔助回答」。
|
||
// 指定的回答(--rules 檔,`ctl model-reply` 寫)先看:system 或最後一則使用者訊息含某條規則的
|
||
// match,就回那條的 reply——AnyBot 自己的子任務(目標評審、自動審核…)也能照劇本回答。
|
||
// reply 裡的 [[call 工具 {JSON}]]:最後一則不是工具結果時照叫(不管這一輪有沒有那個工具,用來看
|
||
// AnyBot 怎麼擋),是工具結果時回 reply 去掉 [[call]] 的字。檔案每個請求重讀,後加的規則先比對。
|
||
// 每個請求寫一行到 --log(JSONL):時間、種類、工具數、system 開頭、最後一則、回了什麼;照規則回的
|
||
// 另外記整則使用者訊息(user_full)。只聽 127.0.0.1。
|
||
//
|
||
// 用法:node fake-model.mjs --port 0 --log requests.jsonl --port-file model.port [--rules rules.json]
|
||
|
||
import http from "node:http";
|
||
import fs from "node:fs";
|
||
|
||
const arg = (name, dflt) => {
|
||
const i = process.argv.indexOf(name);
|
||
return i > 0 && process.argv[i + 1] !== undefined ? process.argv[i + 1] : dflt;
|
||
};
|
||
const PORT = Number(arg("--port", "0"));
|
||
const LOG = arg("--log", "");
|
||
const PORT_FILE = arg("--port-file", "");
|
||
const RULES = arg("--rules", "");
|
||
const MODEL = "fake-model";
|
||
|
||
const log = (entry) => {
|
||
if (LOG) fs.appendFileSync(LOG, JSON.stringify({ t: new Date().toISOString(), ...entry }) + "\n");
|
||
};
|
||
|
||
const textOf = (content) => {
|
||
if (typeof content === "string") return content;
|
||
if (Array.isArray(content)) return content.map((p) => (typeof p === "string" ? p : p?.text ?? "")).join("");
|
||
return "";
|
||
};
|
||
|
||
const CALL = /\[\[call\s+([A-Za-z0-9_.:-]+)\s*(\{[\s\S]*?\})?\s*\]\]/;
|
||
|
||
// The scripted answers (`ctl model-reply`): [{match, reply}], newest last. Read on every request.
|
||
function rules() {
|
||
if (!RULES || !fs.existsSync(RULES)) return [];
|
||
try { const r = JSON.parse(fs.readFileSync(RULES, "utf8")); return Array.isArray(r) ? r : []; } catch (_) { return []; }
|
||
}
|
||
|
||
// What to answer: {text} or {call: {name, args}}.
|
||
function decide(body) {
|
||
const msgs = Array.isArray(body.messages) ? body.messages : [];
|
||
const tools = (Array.isArray(body.tools) ? body.tools : []).map((t) => t?.function?.name ?? t?.name).filter(Boolean);
|
||
const last = msgs[msgs.length - 1] ?? {};
|
||
const lastUser = [...msgs].reverse().find((m) => m.role === "user");
|
||
const userText = textOf(lastUser?.content);
|
||
const system = msgs.filter((m) => m.role === "system").map((m) => textOf(m.content)).join("\n") + (typeof body.system === "string" ? body.system : "");
|
||
const info = { tools: tools.length, system: system.slice(0, 120), last_role: last.role ?? "", user: userText.slice(0, 200) };
|
||
const rule = rules().reverse().find((r) => r && r.match && (system.includes(r.match) || userText.includes(r.match)));
|
||
if (rule) {
|
||
const reply = String(rule.reply ?? "");
|
||
const m = last.role !== "tool" ? reply.match(CALL) : null;
|
||
const ruled = { ...info, kind: "rule", rule: rule.match, user_full: userText.slice(0, 8000), ...(last.role === "tool" ? { tool_result: textOf(last.content).slice(0, 400) } : {}) };
|
||
if (m) {
|
||
try { return { info: ruled, call: { name: m[1], args: m[2] ? JSON.parse(m[2]) : {} } }; } catch (e) { return { info: { ...ruled, kind: "bad-directive" }, text: `FAKE-MODEL:規則裡 [[call]] 的 JSON 看不懂(${e.message})` }; }
|
||
}
|
||
return { info: ruled, text: reply.replace(new RegExp(CALL.source, "g"), "").trim() };
|
||
}
|
||
if (tools.length === 0) return { info: { ...info, kind: "aux" }, text: "FAKE-MODEL 輔助回答" };
|
||
if (last.role === "tool") {
|
||
return { info: { ...info, kind: "after-tool", tool_result: textOf(last.content).slice(0, 200) }, text: `FAKE-MODEL 收到工具結果:${textOf(last.content).slice(0, 80)}` };
|
||
}
|
||
// (AnyBot 帶進訊息的〔相關記憶…〕裡可能有舊的 [[call]]:不算,只看使用者自己打的字。)
|
||
const m = last.role === "user" ? textOf(last.content).replace(/〔[^〕]*〕/g, "").match(CALL) : null;
|
||
if (m) {
|
||
const name = m[1];
|
||
let args = {};
|
||
try { args = m[2] ? JSON.parse(m[2]) : {}; } catch (e) { return { info: { ...info, kind: "bad-directive" }, text: `FAKE-MODEL:[[call]] 的 JSON 看不懂(${e.message})` }; }
|
||
if (!tools.includes(name)) return { info: { ...info, kind: "missing-tool", want: name }, text: `FAKE-MODEL:這一輪沒有 ${name} 這個工具(有:${tools.slice(0, 30).join("、")})` };
|
||
return { info: { ...info, kind: "call" }, call: { name, args } };
|
||
}
|
||
// (AnyBot 在訊息後面加的〔送出時間…〕〔用繁體中文…〕提示不回聲,答案才固定。)
|
||
const said = userText.replace(/〔[^〕]*〕/g, "").replace(/\s+/g, " ").trim();
|
||
return { info: { ...info, kind: "turn" }, text: `FAKE-MODEL 回答:${said.slice(0, 200)}` };
|
||
}
|
||
|
||
let calls = 0;
|
||
function answer(res, body, d) {
|
||
const id = `call_fake_${++calls}`;
|
||
if (body.stream) {
|
||
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "close" });
|
||
const delta = d.call
|
||
? { tool_calls: [{ index: 0, id, type: "function", function: { name: d.call.name, arguments: JSON.stringify(d.call.args) } }] }
|
||
: { role: "assistant", content: d.text };
|
||
res.write(`data: ${JSON.stringify({ id: "fake", object: "chat.completion.chunk", model: MODEL, choices: [{ index: 0, delta }] })}\n\n`);
|
||
res.write(`data: ${JSON.stringify({ id: "fake", object: "chat.completion.chunk", model: MODEL, choices: [{ index: 0, delta: {}, finish_reason: d.call ? "tool_calls" : "stop" }] })}\n\n`);
|
||
res.end("data: [DONE]\n\n");
|
||
return;
|
||
}
|
||
const message = d.call
|
||
? { role: "assistant", content: null, tool_calls: [{ id, type: "function", function: { name: d.call.name, arguments: JSON.stringify(d.call.args) } }] }
|
||
: { role: "assistant", content: d.text };
|
||
res.writeHead(200, { "Content-Type": "application/json" });
|
||
res.end(JSON.stringify({ id: "fake", object: "chat.completion", model: MODEL, choices: [{ index: 0, message, finish_reason: d.call ? "tool_calls" : "stop" }] }));
|
||
}
|
||
|
||
const server = http.createServer((req, res) => {
|
||
let raw = "";
|
||
req.on("data", (c) => (raw += c));
|
||
req.on("end", () => {
|
||
const path = (req.url || "").split("?")[0];
|
||
if (req.method === "GET" && path.endsWith("/models")) {
|
||
log({ method: req.method, path, kind: "models" });
|
||
res.writeHead(200, { "Content-Type": "application/json" });
|
||
return res.end(JSON.stringify({ object: "list", data: [{ id: MODEL, object: "model" }] }));
|
||
}
|
||
if (req.method === "POST" && path.endsWith("/chat/completions")) {
|
||
let body = {};
|
||
try { body = JSON.parse(raw || "{}"); } catch (_) {}
|
||
const d = decide(body);
|
||
log({ method: req.method, path, model: body.model ?? "", stream: !!body.stream, ...d.info, reply: d.call ? { call: d.call } : { text: d.text } });
|
||
return answer(res, body, d);
|
||
}
|
||
log({ method: req.method, path, kind: "unknown" });
|
||
res.writeHead(404, { "Content-Type": "application/json" });
|
||
res.end(JSON.stringify({ error: { message: `fake model: no ${req.method} ${path}` } }));
|
||
});
|
||
});
|
||
|
||
server.listen(PORT, "127.0.0.1", () => {
|
||
const port = server.address().port;
|
||
if (PORT_FILE) fs.writeFileSync(PORT_FILE, String(port));
|
||
console.log(`fake model listening on http://127.0.0.1:${port}/v1`);
|
||
});
|
||
for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => server.close(() => process.exit(0)));
|