示例工程 ch05-message-types

ch05-message-types/01-message-algebra/index.ts

typescript · 4.0 KB

// 01-message-algebra —— 内部转录(AgentMessage)与模型输入(Message)为什么要分两层。
//
// 运行:node --experimental-strip-types index.ts
//
// 这个文件只用 pi-ai + pi-agent-core:
//   1. 通过 declaration merging 给转录加一种只给 UI 看的消息(note)
//   2. 写一个 convertToLlm:把 note 转成 system、把 bashExecution 转成 user、丢掉 hidden
//   3. 断言转换后的每一条都是模型认识的四种形状之一
 
import type { Message } from "@earendil-works/pi-ai";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
 
// 声明合并:往「内部转录」里加一种自定义消息。这里把它做成「只给 UI 的提示」
declare module "@earendil-works/pi-agent-core" {
	interface CustomAgentMessages {
		note: { role: "note"; text: string; hidden: boolean; timestamp: number };
	}
}
 
const transcript: AgentMessage[] = [
	{ role: "system", content: "你是测试助手。", timestamp: 0 },
	{ role: "note", text: "用户正在第 3 次尝试", hidden: false, timestamp: 1 },
	{ role: "user", content: "帮我看看这个 bug", timestamp: 2 },
	{
		role: "assistant",
		content: [
			{ type: "text", text: "我先读文件。" },
			{ type: "toolCall", id: "c1", name: "read", arguments: { path: "a.ts" } },
		],
		api: "stub",
		provider: "stub",
		model: "stub-1",
		usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
		stopReason: "toolUse",
		timestamp: 3,
	},
	{ role: "toolResult", toolCallId: "c1", toolName: "read", content: [{ type: "text", text: "const a = 1;" }], isError: false, timestamp: 4 },
	{ role: "note", text: "内部调试信息,不该给模型看", hidden: true, timestamp: 5 },
];
 
/** 约定:必须返回四种 Message 之一,且不得抛异常。 */
function convertToLlm(messages: AgentMessage[]): Message[] {
	const output: Message[] = [];
	for (const message of messages) {
		switch (message.role) {
			case "note":
				if (message.hidden) break; // 只给 UI 的,直接丢弃
				output.push({
					role: "system",
					content: [{ type: "text", text: `[note] ${message.text}` }],
					timestamp: message.timestamp,
				});
				break;
			case "system":
			case "user":
			case "assistant":
			case "toolResult":
				output.push(message);
				break;
		}
	}
	return output;
}
 
const converted = convertToLlm(transcript);
 
console.log("转录(AgentMessage):", transcript.map((m) => m.role).join(" → "));
console.log("转换后(Message):", converted.map((m) => m.role).join(" → "));
console.log("首条 system 内容:", JSON.stringify(converted[0]));
 
const ALLOWED = new Set(["system", "user", "assistant", "toolResult"]);
const ok = (label: string, pass: boolean): void => {
	console.log(`${pass ? "✓" : "✗"} ${label}`);
	if (!pass) process.exitCode = 1;
};
 
ok("转录里出现了 5 种角色(含自定义 note)", new Set(transcript.map((m) => m.role)).size === 5);
ok("转换后只剩四种合法形状", converted.every((m) => ALLOWED.has(m.role)));
ok("hidden 的 note 被丢弃(6 条 → 5 条)", transcript.length === 6 && converted.length === 5);
ok("可见的 note 变成了 system 消息", converted.some((m) => m.role === "system" && JSON.stringify(m).includes("[note]")));
ok("toolResult 的 toolCallId 保持不变", converted.find((m) => m.role === "toolResult")?.toolCallId === "c1");
ok("assistant 里的 toolCall 原样保留", JSON.stringify(converted).includes('"name":"read"'));
ok("转换是纯函数:不改动原数组", transcript.length === 6 && transcript[1]?.role === "note");
 
// 配对不变量:每个 toolCall 都要有 toolResult
const callIds = converted.flatMap((m) =>
	m.role === "assistant" ? m.content.filter((c) => c.type === "toolCall").map((c) => c.id) : [],
);
const resultIds = converted.flatMap((m) => (m.role === "toolResult" ? [m.toolCallId] : []));
ok("toolCall 与 toolResult 一一配对", callIds.length === resultIds.length && callIds.every((id) => resultIds.includes(id)));
 
console.log("✓ OK");