从一个有界的模型循环里返回一个匹配 schema 的值
用一个脚本化的 provider 在 pi-agent-core 1.0.4 上驱动 step():一次有效的 submit 用一次请求结束运行,而其他每一个出口都是一个 StepFailed kind。
随机一步是一个带类型的函数:文本进,一个匹配你的 TypeBox schema 的值出,没有第三种结果。模型只能通过调用一个 submit 工具来结束,那个工具的参数就是那个 schema,所以文字无法从接缝处漏出去。本页用一个脚本化的 provider 在 pi-agent-core 1.0.4 上运行那个标准的 step.ts。
运行它
唯一的出口是 submit 工具;terminate: true 是结束循环的那个提示(标准 step.ts 的摘录,完整文件在下面链接):
const submit: AgentTool = {
name: "submit",
label: "Submit",
description: "Submit the final answer. This ends the task. Call it exactly once.",
parameters: schema,
async execute(_id, params) {
// The first valid submission is the answer. A later one cannot
// overwrite it, so a model that submits twice cannot retroactively
// change the value this call returns.
if (result === undefined) result = params as Static<S>;
return { content: [{ type: "text", text: "accepted" }], details: undefined, terminate: true };
},
};参数在 execute() 运行之前就被校验,所以它只会看到有效值。那些边界是本书的模式,不是 Pi 的契约:maxAttempts 数无效提交,maxTurns 数总轮数:
let failures = 0;
let turns = 0;
let hitTurnLimit = false;
agent.subscribe((e) => {
if (e.type === "tool_execution_end" && e.toolName === "submit" && e.isError && ++failures >= maxAttempts) {
agent.abort();
}
if (e.type === "turn_end" && ++turns >= maxTurns) {
hitTurnLimit = true;
agent.abort();
}
});在 await agent.prompt(input) 之后没有第三种结果:一个已存下的提交会被返回,否则就抛出一个带着 kind 的 StepFailed——invalid-submissions、turn-limit、provider(一次失败的请求),或 no-submit。
预期结果
每一行都是已观察的:step.test.ts(Pi 1.0.4,脚本化的响应)锁定每一行;最后四行之所以存在,是因为第一个版本把它们搞错了。
| 脚本化的模型做什么 | 结果 |
|---|---|
| 一次提交一个有效值 | 在 1 次请求之后返回它;terminate 省掉了那次跟进 |
| 先提交无效的,再提交有效的 | 那次无效的调用以一个错误返回,而模型修好了它 |
| 一直提交无效值 | 停在 maxAttempts 上;execute() 从未见过一个非有效值 |
用文字回答,没有 submit |
StepFailed kind 为 no-submit——从来不是一个静默的空值 |
| (两个步骤) | 一步的输出被序列化后,就是下一步的输入 |
| 用一个查找工具,然后提交 | 允许;它仍然必须以一次有效的 submit 结束 |
| 遇到一次失败的请求 | StepFailed kind 为 provider——限流不是一次模型决定 |
| 从不提交 | 被 maxTurns 拦住(kind 为 turn-limit);maxAttempts 永远不动 |
最后一行是第一个版本崩掉的地方。一个批次只有在每个已完成的结果都同意时才提前结束,所以 submit 加上一个非终止的查找会存下一个值并继续循环——一个读作 && result === undefined 的守卫在那时就关掉了。修好的守卫丢掉了那个子句,仍然返回已承诺的值,而 maxTurns 成立。
机制与局限
有文档记载: AgentTool、执行前的参数校验、terminate 语义(“every finalized tool result in the batch”)、abort(),以及抛出即失败(pi-agent-core README 与声明,1.0.4)。已观察:step.test.ts 通过一个 Agent 驱动真正的 step(),并对上面每一行做出断言,包括一次混合批次中的无效提交只耗费一次尝试。本书提出:step() 这个抽象和那些边界数字。
一个匹配 schema 的值不是一个为真的值:schema 约束形状,不约束内容。这是一次 faux provider 运行——关于一个真实模型有多大比例第一次就提交有效值,它什么也没说。
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.