看智能体循环调用一个工具
用一个脚本化的 provider、一个字数统计工具和两轮助手回复,运行真实的 Pi 1.0.4 智能体内核。
没有凭据你也可以观察这个循环。provider 脚本化助手的响应;真正的 Agent 执行工具并发出事件。这证明的是编排(orchestration),而不是真实模型对工具的选择或对其结果的解释。
运行它
使用 Node.js 22.18 或更高版本,它内置了 TypeScript 剥离能力。在一个空目录里:
npm init -y
npm pkg set type=module
npm install @earendil-works/pi-agent-core@1.0.4 @earendil-works/pi-ai@1.0.4把下面这个完整的文件保存为 agent-core.ts,然后运行 node agent-core.ts。
它是本书规范示例的精确副本,不是一个替代用的测试骨架。
import { Agent, type AgentTool } from "@earendil-works/pi-agent-core";
import {
Type,
createModels,
fauxAssistantMessage,
fauxProvider,
fauxText,
fauxToolCall,
} from "@earendil-works/pi-ai";
// The provider layer: a scripted stand-in for a model.
const faux = fauxProvider();
const models = createModels();
models.setProvider(faux.provider);
// A tool is a name, a schema and an execute(). Nothing here knows about Pi.
const WordCountParams = Type.Object({ text: Type.String() });
const wordCount: AgentTool<typeof WordCountParams> = {
name: "word_count",
label: "Word Count",
description: "Count the words in a string.",
parameters: WordCountParams,
async execute(_id, params) {
const n = params.text.trim().split(/\s+/).filter(Boolean).length;
return { content: [{ type: "text", text: String(n) }], details: { words: n } };
},
};
// Turn 1 asks for the tool. Turn 2 answers from its result.
faux.setResponses([
fauxAssistantMessage([fauxToolCall("word_count", { text: "the quick brown fox" })], { stopReason: "toolUse" }),
fauxAssistantMessage([fauxText("Four words.")]),
]);
// The agent core: loop, messages, state, tool execution, events.
const agent = new Agent({
initialState: { systemPrompt: "You count words.", model: faux.getModel(), tools: [wordCount] },
streamFn: models.streamSimple.bind(models),
});
agent.subscribe((e) => {
if (e.type === "tool_execution_end") console.log("tool:", e.toolName, JSON.stringify(e.result.details));
if (e.type === "message_end" && e.message.role === "assistant") console.log("stop:", e.message.stopReason);
});
await agent.prompt("How many words in 'the quick brown fox'?");预期结果
现有的第 1 章测试在 Pi 1.0.4 上断言的就是这段 stdout:
stop: toolUse
tool: word_count {"words":4}
stop: stop| 事件 | 你了解到什么 |
|---|---|
第一次助手以 toolUse 停止 |
脚本化的请求点名了 word_count |
| 工具执行结束 | 真正的工具返回了 { "words": 4 } |
| 第二次助手停止 | 后续一轮助手回复完成了 |
机制与局限
**有文档记载:**锁定的 agent-core 导出的声明描述了 Agent、AgentTool、事件订阅和工具执行。**已观察:**规范的 agent-core.test.ts 运行这个文件,并检查上面那三行。第二条响应被脚本化为 “Four words.";它不是模型推理的证据。
完整源码与测试 维护在 Pi 仓库中。站点的来源检查会捕捉源码漂移。
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.