示例工程 ch19-codemode-tool-search

ch19-codemode-tool-search/01-codemode-hello/index.ts

typescript · 2.8 KB

// 01-codemode-hello —— 让「模型写的脚本」在 QuickJS 沙箱里编排工具。
//
// 运行:node --experimental-strip-types index.ts
//
// 关键观察:一段脚本里调了 2 个工具,但对模型来说只有 1 次「工具调用」。
// 这就是 codemode 的核心收益:把 N 次往返压成 1 次。
 
import { InlineCodemodeSandbox, loadQuickJSWasm, type CodemodeTool } from "@earendil-works/pi-codemode";
 
const USERS: Record<string, { name: string; team: string }> = {
	u1: { name: "Ada", team: "core" },
	u2: { name: "Linus", team: "kernel" },
	u3: { name: "Grace", team: "navy" },
};
 
const tools: CodemodeTool[] = [
	{
		name: "list_users",
		description: "列出全部用户 id",
		inputSchema: { type: "object", properties: {} },
		async execute() {
			return Object.keys(USERS);
		},
	},
	{
		name: "get_user",
		description: "按 id 取用户",
		inputSchema: {
			type: "object",
			properties: { id: { type: "string" } },
			required: ["id"],
		},
		async execute(args) {
			const id = String((args as { id?: string }).id ?? "");
			const user = USERS[id];
			if (!user) throw new Error(`用户不存在:${id}`);
			return user;
		},
	},
];
 
// Inline 沙箱必须显式给 wasm;默认路径只在 worker 版沙箱里自动解析
const sandbox = new InlineCodemodeSandbox({ tools, wasm: await loadQuickJSWasm(), timeoutMs: 5000 });
 
// 模型「写」的脚本:先列用户,再逐个取详情,最后汇总
const script = `
const ids = await tools.list_users();
const users = [];
for (const id of ids) {
  users.push(await tools.get_user({ id }));
}
return users.filter((u) => u.team !== "navy").map((u) => u.name);
`;
 
const result = await sandbox.execute(script);
await sandbox.close();
 
const calls = result.calls.map((call) => `${call.name}`);
 
console.log("ok:", result.ok);
console.log("脚本返回值:", JSON.stringify(result.ok ? result.value : result.error));
console.log("宿主侧记录的工具调用:", calls.join(" → "));
console.log("工具调用次数:", result.calls.length);
console.log("脚本对模型的「往返次数」:1(一段脚本就是一次调用)");
 
const ok = (label: string, pass: boolean): void => {
	console.log(`${pass ? "✓" : "✗"} ${label}`);
	if (!pass) process.exitCode = 1;
};
 
ok("脚本执行成功", result.ok === true);
ok("返回值过滤掉了 navy 团队", JSON.stringify(result.ok ? result.value : null) === '["Ada","Linus"]');
ok("宿主记录到 1 次 list_users", calls.filter((name) => name === "list_users").length === 1);
ok("宿主记录到 3 次 get_user", calls.filter((name) => name === "get_user").length === 3);
ok("共 4 次工具调用压在 1 段脚本里", result.calls.length === 4);
ok("调用顺序与脚本一致", calls.join(",") === "list_users,get_user,get_user,get_user");
 
console.log("✓ OK");