chat 0.1.12: recall tools from unspaced Chinese questions in large MCP catalogs (duhu2000, #872)
The chat page picks up to 12 tools from a large MCP catalog. It now splits unspaced Chinese into two-character terms instead of treating the whole question as one word. Terms are weighted by how rare they are in the catalog (IDF), and a tool named exactly in the question, hyphenated names included, is boosted to the top. The selection moves into lib/tool-selection.mjs with its own tests. page-chat goes to 0.1.12. Run at d10e93a62832e31ead84ddef438b615b13935e26 merged onto main1aab125bf, on a separate macOS machine (bun 1.4.2, sandbox HOME): - packages/chat `bun test`: 75 pass, 1 skip, 0 fail. - `bun scripts/check.mjs`: exit 0. - Root `bun test`: 21 fail and 4 errors in devin, zcode and window-warmup, none in chat. Main1aab125bfshows the same 21 and 4 in the same tests. The devin and zcode ones refuse a HOME that isn't from `mktemp -d`. - Broken by hand, one at a time: without the exact-name boost, "exact identifier outranks…" goes red. With IDF replaced by 1, "rare term outranks…" goes red. Without `-` in the Latin term regex, the exact-identifier test goes red. Version: page-chat is served from the dist branch, where the newest is 0.1.11.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
// magpie-chat 的服务:给窗口里的对话页提供 /api/*,并把聊天请求转给 magpie 网关。
|
||||
// 只用内置模块,不装依赖。
|
||||
|
||||
import { selectTools } from "./tool-selection.mjs";
|
||||
import { createServer } from "node:http";
|
||||
import { randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
@@ -393,21 +394,7 @@ async function runChat({ res, body, settings, store, options }, controllers) {
|
||||
}
|
||||
const last = history[history.length - 1];
|
||||
const q = String(typeof last?.userText === "string" ? last.userText : last?.content || "").toLowerCase();
|
||||
const words = q.split(/[^a-z0-9\u4e00-\u9fff]+/).filter((w) => w.length >= 3);
|
||||
const scored = all.map((t) => {
|
||||
const hay = (t.name + " " + (t.description || "")).toLowerCase();
|
||||
let score = 0;
|
||||
for (const w of words) if (hay.includes(w)) score += w.length > 4 ? 2 : 1;
|
||||
return { t, score };
|
||||
}).filter((x) => x.score > 0).sort((a, b) => b.score - a.score);
|
||||
const MAX_TOOLS = 12;
|
||||
tools = scored.slice(0, MAX_TOOLS).map((x) => x.t);
|
||||
if (tools.length < 3) {
|
||||
// 问得太笼统时给一组最通用的,但仍然封顶
|
||||
const common = /^(get|list|search|read|fetch|query)_|(_search|_list|_get)$/;
|
||||
const extra = all.filter((t) => common.test(t.rawName) && !tools.includes(t)).slice(0, 8);
|
||||
tools = tools.concat(extra).slice(0, MAX_TOOLS);
|
||||
}
|
||||
tools = selectTools(all, q);
|
||||
if (all.length > tools.length) {
|
||||
toolNote = `(这次提供了 ${tools.length}/${all.length} 个工具:按你的问题挑的)`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// Keep schemas bounded, but do not treat a whole unspaced Chinese question
|
||||
// as one word. Rare matching terms outrank boilerplate repeated in catalogs.
|
||||
export function selectTools(all, query, limit = 12) {
|
||||
const q = String(query).toLowerCase();
|
||||
const terms = new Set(q.match(/[a-z0-9_-]+/g)?.filter(w => w.length >= 3) || []);
|
||||
for (const run of q.match(/[\u4e00-\u9fff]+/g) || []) {
|
||||
for (let i = 0; i < run.length - 1; i++) terms.add(run.slice(i, i + 2));
|
||||
}
|
||||
const rows = all.map(t => ({ t, hay: `${t.name} ${t.description || ""}`.toLowerCase(), score: 0 }));
|
||||
for (const term of terms) {
|
||||
const hits = rows.filter(r => r.hay.includes(term));
|
||||
const weight = Math.log(1 + all.length / Math.max(1, hits.length));
|
||||
for (const row of hits) row.score += weight;
|
||||
}
|
||||
for (const row of rows) {
|
||||
// Explicit tool identifiers must win even over verbose descriptions.
|
||||
const name = String(row.t.rawName || row.t.name).toLowerCase();
|
||||
if (terms.has(name)) row.score += 1000;
|
||||
}
|
||||
const selected = rows.filter(r => r.score > 0).sort((a, b) => b.score - a.score)
|
||||
.slice(0, limit).map(r => r.t);
|
||||
if (selected.length < 3) {
|
||||
const common = /^(get|list|search|read|fetch|query)_|(_search|_list|_get)$/;
|
||||
selected.push(...all.filter(t => common.test(t.rawName) && !selected.includes(t)).slice(0, 8));
|
||||
}
|
||||
return selected.slice(0, limit);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-chat",
|
||||
"version": "0.1.11",
|
||||
"version": "0.1.12",
|
||||
"description": "在 magpie 窗口里加一个「对话」页面:用 magpie 自己的模型、MCP 服务器、指令和技能聊天,支持图片与 LaTeX。A chat page inside magpie's window: talk with magpie's own models, MCP servers, instructions and skills, with images and LaTeX.",
|
||||
"author": "Magic_zero (https://github.com/Magiczerowxy)",
|
||||
"files": [
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { selectTools } from "./lib/tool-selection.mjs";
|
||||
|
||||
const tool = (name, description) => ({name: `example_${name}`, rawName: name, description});
|
||||
const historical = tool("get_historical_patent", "查询企业历史专利信息");
|
||||
const current = tool("get_current_patent", "查询企业当前专利信息");
|
||||
const catalog = [...Array.from({length: 184}, (_, i) => tool(`get_record_${i}`, "查询企业基本信息")), current, historical];
|
||||
|
||||
test("unspaced Chinese recalls historical tools from a 186 tool catalog", () => {
|
||||
const selected = selectTools(catalog, "请查询示例科技股份有限公司的历史专利");
|
||||
expect(selected[0]).toBe(historical);
|
||||
expect(selected.length).toBeLessThanOrEqual(12);
|
||||
});
|
||||
test("current and historical requests rank differently", () => {
|
||||
expect(selectTools(catalog, "查询企业当前专利")[0]).toBe(current);
|
||||
});
|
||||
test("explicit raw identifier wins over boilerplate", () => {
|
||||
expect(selectTools(catalog, "只调用 get_historical_patent 查询企业基本信息")[0]).toBe(historical);
|
||||
});
|
||||
test("English keywords still select matching tools", () => {
|
||||
const wanted = tool("search_issues", "Search project issues");
|
||||
expect(selectTools([...catalog, wanted], "search project issues")[0]).toBe(wanted);
|
||||
});
|
||||
test("empty query preserves bounded fallback without duplicate tools", () => {
|
||||
const selected = selectTools(catalog, "");
|
||||
expect(selected.length).toBe(8);
|
||||
expect(new Set(selected).size).toBe(selected.length);
|
||||
expect(selectTools([], "历史专利")).toEqual([]);
|
||||
});
|
||||
|
||||
// Adversarial fixtures: each assertion fails if its scoring rule is removed.
|
||||
test("exact identifier outranks a description matching more query terms", () => {
|
||||
const exact = tool("get-patent", "Read patents");
|
||||
const distractor = tool("search_records", "get-patent company historical records");
|
||||
expect(selectTools([distractor, exact], "get-patent company historical records", 1)).toEqual([exact]);
|
||||
});
|
||||
test("rare term outranks two widespread boilerplate terms", () => {
|
||||
const common = Array.from({length: 30}, (_, i) => tool(`get_common_${i}`, "company records"));
|
||||
const rare = tool("get_special", "patent");
|
||||
expect(selectTools([...common, rare], "company records patent", 1)).toEqual([rare]);
|
||||
});
|
||||
Reference in New Issue
Block a user