随机一步是一个类型化函数
智能体循环自己决定它何时结束;类型化步骤把那个决定拿走,办法是让唯一的出口成为一次必须匹配 schema 的调用,然后再把各步骤当作普通函数串起来。
智能体给出的答案是一段文字,而文字不是可以在其上建造的东西。
你无法把一段话传给下一个函数。不在它上面解析就没法做分支判断,而解析就意味着猜。模型是因为认定自己结束了才结束的,用的是它自己选中的那些词。它下游的一切都继承了这个猜测。
第 36 章为单次调用解决了这个问题。本章为循环解决它。结果是本书中最可复用的那个想法,而它装得进一个函数里。
形状
随机一步是一个函数:它的输入是文本,而它的输出是你声明过的一个值:
step(models, model, system, input: string, schema) -> Promise<Static<schema>>
models 和 model 是这一步跨越层边界的方式:它们是 pi-ai 那个集合,以及智能体内核将要调用的那个模型。输入是文本。带类型的值只存在于出口这一侧。
它里面的模型可以想干什么就干什么,包括调用工具、改变主意以及出错。它做不到的,是返回任何不匹配 schema 的东西。要么调用方拿到一个有效值,要么调用方拿到一个异常。不存在第三种结果,让一个半有效的段落漏出去。这是一个关于返回物的形状的陈述,而那个异常带着一个 kind,好让调用方能区分一次 provider 失败和一个没有照办的模型。
实现
import { Agent, type AgentTool } from "@earendil-works/pi-agent-core";
import type { Model, Models, Static, TSchema } from "@earendil-works/pi-ai";
export interface StepOptions {
/** How many invalid submissions to tolerate before giving up. */
maxAttempts?: number;
/** How many model turns to allow in total, whatever they do. Bounds a model that never submits. */
maxTurns?: number;
extraTools?: AgentTool[];
}
// `kind` says which bound or failure ended the step, so a caller can retry a provider
// failure and not a model that answered in prose.
export type StepFailure = "provider" | "invalid-submissions" | "turn-limit" | "no-submit";
export class StepFailed extends Error {
readonly kind: StepFailure;
constructor(message: string, kind: StepFailure) {
super(message);
this.kind = kind;
}
}
// One stochastic step as a function: text in, a value that matches `schema` out.
// The model finishes only by calling `submit`. The agent core validates the
// arguments before execute() runs, so execute() only ever sees a valid value.
export async function step<S extends TSchema>(
models: Models,
model: Model<any>,
system: string,
input: string,
schema: S,
options: StepOptions = {},
): Promise<Static<S>> {
const maxAttempts = options.maxAttempts ?? 3;
const maxTurns = options.maxTurns ?? 10;
let result: Static<S> | undefined;
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 };
},
};
const agent = new Agent({
initialState: { systemPrompt: system, model, tools: [submit, ...(options.extraTools ?? [])] },
streamFn: models.streamSimple.bind(models),
});
// An invalid submission comes back to the model as an error result, so the
// loop re-asks by itself. Bound it, because a model can repeat a mistake.
// maxAttempts bounds invalid submissions only. A model that never calls submit
// produces no invalid submission, so the turn count is the bound that covers it.
//
// maxTurns bounds the whole run, so it must fire whether or not a submission
// has been stored. It is not conditional on `result === undefined`, and that
// is the load-bearing detail: submit returns `terminate: true`, but a batch
// only ends the turn when every completed result in it agrees (chapter 17).
// A response carrying submit *and* a non-terminating tool therefore stores a
// result and keeps looping, and a bound that switched off once a result
// existed would stop holding exactly then.
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);
// A stored submission is already schema-valid, so it is the answer. Returning
// it after enforcing the bound is deliberate: the bound is there to stop the
// loop, not to reject a value the model already committed to.
if (result !== undefined) return result;
if (failures >= maxAttempts) throw new StepFailed(`no valid submission after ${failures} attempt(s)`, "invalid-submissions");
if (hitTurnLimit) throw new StepFailed(`no submission after ${turns} turn(s)`, "turn-limit");
// A failed request is not a model decision. It ends the run with the error on the final message.
const last = agent.state.messages.findLast((m) => m.role === "assistant");
if (last && (last.stopReason === "error" || last.stopReason === "aborted")) {
throw new StepFailed(`model call failed: ${last.errorMessage ?? last.stopReason}`, "provider");
}
throw new StepFailed(failures ? `no valid submission after ${failures} attempt(s)` : "the model finished without calling submit", failures ? "invalid-submissions" : "no-submit");
}
它很短,因为智能体内核已经做了大部分的工作。有三个机制在干活,而每一个都有文档记载。
唯一的出口是一个工具。 模型被告知 submit 会结束任务。它的参数就是你传进来的那个 schema,所以模型被要求产出的东西,恰好就是这个函数返回的类型。TypeScript 类型与运行时 schema 来自同一个 TypeBox 定义,因此它们不可能不一致。
参数在 execute() 运行之前就被校验。 README 说内核会在 beforeToolCall 和执行之前解析并校验参数。所以 result = params 那一行永远只会看到有效值。你不写校验,你写 schema。
terminate: true 在提交时结束这次运行。 一个工具结果可以带上 terminate: true,作为循环应该跳过它那次自动跟进请求的提示。内核只在一个批次里每一个已最终确定的工具结果都设了它的时候才尊重这个提示,所以如果模型在提交之外还发起了另一次调用,循环就会照常继续。没有它,一次成功的提交之后还会跟着一次请求,模型在那里面说 “Done!",而你要为这句话付钱。
测试确立了哪些东西
十四个测试,对着 pi-agent-core 1.0.4 运行。每一个都锁定一条性质。最后六行之所以存在,是因为一次独立评审发现 step() 的第一个版本把它们搞错了,而那六个中的第一个是一个被承诺过、代码却没有真正守住的边界。
| 测试 | 它表明什么 |
|---|---|
| 有效提交 | 一次请求,而不是两次。terminate 真的省掉了那次跟进 |
| 先无效,再有效 | 循环自己修好了它自己:那个无效的提交作为一个错误结果回到模型那里,而它又试了一次 |
| 反复无效 | 停在 maxAttempts 上,而 execute() 从未见过任何值 |
只有文字,没有 submit |
StepFailed,而不是一个空结果或半截结果 |
| 两个步骤 | 一步的输出被序列化后,就是下一步的输入文本 |
| 一次失败的请求 | 带 kind: "provider" 和那条 provider 消息的 StepFailed,而不是 “the model finished without calling submit” |
| 一个从不提交的模型 | 被 maxTurns 叫停,kind 为 "turn-limit"。maxAttempts 管不住这个,因为从未发生过无效提交 |
只有文字,没有 submit |
kind: "no-submit" |
submit 与一个非终止工具同批 |
maxTurns 依然成立。被提交的值会被返回,而请求数恰好是 maxTurns |
| 混合批次,然后这次运行失败 | 一个已经承诺的值能在之后一次 provider 失败后存活,因为它已经被存下来了 |
| 提交了两次 | 第一个有效提交胜出;后一个无法覆盖它 |
| 混合批次中的无效提交 | 只花费一次尝试,而不是批次里每个工具各一次 |
| 混合批次中反复无效,直到耗尽 | 尝试预算依然以 kind: "invalid-submissions" 结束这次运行 |
三种花掉同样工作的方式
类型化步骤不止一种形状。差别在于谁决定这一步结束了,而这些差别恰好就是边界出错的地方。
| 形状 | 谁结束它 | 典型请求数 | 失败模式 |
|---|---|---|---|
| 一次请求(第 36 章) | 请求自己结束 | 恰好 1,否则就是没成 | 返回文字,或一个错误值。根本没有值 |
| 有界循环(本章) | submit,或一个边界 |
1 到 maxTurns |
用文字回答;提交无效的东西;和一个非终止工具一起提交 |
| 开放式智能体(第 37 章) | 模型自己决定 | 没有上限就是无界 | 一直干活。或者一直搜索。除了你,没有什么能拦住它 |
flowchart LR
I["输入"] --> R1["请求 1"]
R1 -->|"工具调用"| X["全部执行"]
X -->|"每个结果都 terminate"| E["完成"]
X -->|"并非都同意"| R2["请求 2"]
R2 -->|"turn_end"| B{"turns >= maxTurns?"}
B -->|否| R1
B -->|"是"| AB["中止"]
E --> V["匹配 schema 的值或 StepFailed"]
AB --> V
R2 -->|turn_end| B 这条边就是坏掉的那一条。边界是靠数轮次到达的,然后只检查一个结果是否存在——于是混合批次里的一次提交就把边界关掉了。指向 V 的那些箭头才是本章实际的契约:两个出口,而其中一个是异常。
上表第二行值得再仔细看一眼,因为 step() 里没有任何东西实现重试。一次无效提交就是一个 isError 工具结果。模型会看到那个错误,而模型通常会修好出错的那个参数。那就是循环在干它的日常工作,只不过指向的是你的 schema。
第三行之所以存在,是因为模型可能重复犯同一个错。没有边界的话,一个反复提交同一个无效值的模型会一直循环,直到某个请求上限或一张账单拦住它。step() 从 tool_execution_end 事件中数失败次数,并调用 agent.abort()。这个边界是本书提出的,不是有文档记载的。它是一个模式,而数字由你来选。
maxAttempts 只约束无效提交。一个永远调用查找工具的模型从不提交任何无效的东西,所以那个计数永远不动。这个函数的第一个版本没有任何别的边界:对着一个从不提交的脚本化模型,在默认 maxAttempts 为 3 的情况下,它发出了 31 次请求。这就是为什么 step() 还数 turn_end 事件并在 maxTurns 处停下。两个边界都是本书的模式,不是 Pi 的契约。
同一次评审还发现,一次失败的请求过去会以 “the model finished without calling submit” 的形式浮现,这等于把一次限流描述成模型做出的决定。一次失败的请求会以一条 stopReason 为 error 或 aborted 的最终助手消息结束这次运行(第 36 章的 “failure is a value”),而 step() 现在会读那条消息并抛出 kind: "provider"。pi-ai 也带着一个正好针对这种失败的重试层;第 40 章讲它该放在哪里。
那个不曾是边界的边界
轮次计数器原本写作 if (++turns >= maxTurns && result === undefined)。那个守卫看着无害,而它并非如此:它意味着轮次边界在一个提交被存下的那一刻就不再适用。
第 17 章的批次规则才是把它变成一个真实缺陷的东西。submit 返回 terminate: true,但内核只在一个批次里每一个已最终确定的结果都同意时才尊重它。所以一个在一次响应里调用 submit 和一个查找工具的模型,会存下一个有效答案并让循环继续跑——而从那一刻起轮次上限就再也不响了。
在 1.0.4 上对着未修复的代码观察:在 maxTurns: 2、且一个脚本化模型每轮都返回 submit 加上 lookup 的情况下,step() 发出了 七 次请求,并返回了被提交的值。一个在注释里被描述为 “how many model turns to allow in total, whatever they do” 的上限,实际上是 “how many turns to allow before the first valid submission”。
修复方式是把 result === undefined 从守卫里去掉,然后决定一个值存在之后边界意味着什么。当时有三种选择:
- 无视存下的值并抛出
turn-limit。对超支是诚实的,但它丢掉了一个模型已经承诺过的、匹配 schema 的答案。 - 继续返回它,并说出来。边界的职责是停下循环;这个值是否可信是另一个问题,而 schema 已经回答过它了。
- 记录两者都发生了,并报告一个不同的 kind。
本章选第二种,因为它才是能组合的那一个。一个在 kind: "turn-limit" 上重试的调用方是在问 “did the model fail to answer?",而一个已存下的提交意味着它回答了。上表第九行锁定了这一点。
测试还锁定了另外两点,两者都关于同一个批次。一次批次中的无效提交算一次尝试,而不是每个工具各一次,所以在那个修复轮里混入一次查找,不会把预算烧掉两遍。而一次有效提交之后跟着一次 provider 失败,它依然会被返回,因为 result 在失败之前就被赋值了;一个存下的值是循环已经做出的承诺。
串接
因为每一步都有一个声明的输出类型,你拿回来的值是带类型的,而你会把它作为文本传给下一步,由你自己序列化:
const triage = await step(models, model, "Triage.", report, Triage);
const action = await step(models, model, "Write the next action.", JSON.stringify(triage), Action);
这里没有框架,也不需要框架。从每一步流出的数据是一个普通对象,而怎么把它写进下一个提示词由你决定。它并没有被类型化进下一步:JSON.stringify 在那个接缝处把类型抹掉了。你可以记录它、存储它、对它断言、在 triage.severity 上分支,或者干脆跳过第二步。模型永远看不到任何你没有选择放进下一个提示词里的东西,所以步骤之间没有夹带任何隐藏的对话。那与一场漫长的聊天正好相反,而且是刻意的:每一步都从一份空的转录记录和你给它的输入开始。
每次调用都构建自己的 Agent,而 result 是那次调用的一个局部变量。两个步骤不共享状态,所以互不依赖的步骤可以一起跑:
const [a, b] = await Promise.all([step(/* ... */), step(/* ... */)]);
本书提出,附带一个告诫: 文档里没有任何东西承诺这对每一个 provider 都安全。尤其是限流,要由你自己处理。
一步之内的工具
step() 接受 extraTools。一个需要查点东西的步骤,会把第 37 章的那个工具放在 submit 旁边:
const out = await step(models, model, system, input, EvidenceAssessment, {
extraTools: [lookupEvidence(corpus)],
});
现在这一步是一个出口带类型的小智能体。模型可以按需要调用 lookup_evidence 任意多次,而循环只在它带着一个有效评估调用 submit 时才结束。这是第 36 章的单次调用与第 37 章的开放循环相遇的点,而作为默认选择,它是两者中更有用的那一个。
一个类型给不了你的东西
一个匹配 schema 的值,不是一个为真的值。schema 说 confidence 是 0 到 1 之间的一个数。它并没有说模型应该自信。它说 citations 是一个字符串数组。它并没有说那些字符串存在于证据之中。
那道缺口是真实存在的,而接下来两章正走向它。一步让答案的形状成为一个契约。它没有让答案的内容也成为契约。你用这一步之后的普通代码来合上缺口,那是确定性的、免费的:
if (!assessment.citations.every((c) => evidence.includes(c))) throw new Error("invented citation");
第 40 章会做这件事,并用它来决定一条流水线里哪里信任模型、哪里检查模型。
它不是什么
它不是一个多智能体系统。一个智能体跑起来、结束、然后被丢弃。选用 “step” 这个词而不是 “agent”,是因为关于组合没有任何一样东西依赖于这些步骤是智能体。一个步骤可能是一次 complete() 调用,如第 36 章所示。它可能是一个带工具的循环。它可能是一个从不调用模型的普通函数。第 40 章把三者混在一起。
它也不保证成功。step() 可能失败,而它会带着 StepFailed 大声失败。一个不能容忍失败的调用方需要一条策略:重试这一步、换一个模型、上报给一个人,或者停下来。其中哪个才对是一个应用层决定,而这个函数刻意不做这个决定。
你能和不能论断什么
有文档记载: AgentTool、执行前的参数校验、terminate 语义(包括 “every finalized tool result in the batch”)、abort(),以及抛出即失败(pi-agent-core README 与声明,1.0.4)。
已观察: 测试表的每一行,在 1.0.4 上以脚本化的响应运行。这表明代码处理了每一种情况。它并不表明一个真实模型有多大比例能在第一次就提交一个有效值。第 41 章就是讲怎么测量这个的。
本书提出: step() 这个抽象、maxAttempts 这个边界,以及并行运行互不依赖的步骤。
下一章
现在你可以用一个模型构建出一个带类型的函数了。下一个问题不是关于步骤,而是关于控制:在循环里,你能在哪里介入?step() 用了一个钩子,agent.subscribe(),而且是在事后用的。有些决定必须在它们所要决定的那件事发生之前做出。
第 39 章会列出智能体内核允许你干预的每一个点,以及每一个点还能改变什么。