AnyBot/.claude/skills/verify-anybot/scripts/fake-model.mjs

110 lines
6.0 KiB
JavaScript
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
// 驗證用的假模型:OpenAI 相容的 /v1/chat/completions,回固定答案,不連任何真的模型服務。
// AnyBot 的「自訂(OpenAI 相容)」供應商指到這裡(ctl up 用 `setup --seed` 設好)。
//
// 規則(只看最後一則訊息,所以不會無限迴圈):
// - 最後一則是工具結果 → 文字「FAKE-MODEL 收到工具結果:…」,這一輪結束。
// - 使用者訊息裡有 [[call 工具 {JSON}]] → 叫那個工具(這一輪的工具清單裡要有)。
// - 其他 → 文字「FAKE-MODEL 回答:<使用者那句>」。
// - 沒帶工具的請求(AnyBot 自己的小工作:摘要、記憶、標題…)→ 文字「FAKE-MODEL 輔助回答」。
// 每個請求寫一行到 --log(JSONL):時間、種類、工具數、最後一則、回了什麼。只聽 127.0.0.1。
//
// 用法:node fake-model.mjs --port 0 --log requests.jsonl --port-file model.port
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 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 "";
};
// 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 info = { tools: tools.length, last_role: last.role ?? "", user: userText.slice(0, 200) };
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)}` };
}
const m = last.role === "user" ? textOf(last.content).match(/\[\[call\s+([A-Za-z0-9_.:-]+)\s*(\{[\s\S]*?\})?\s*\]\]/) : 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)));