Example

从一次模型调用拿到一个类型化的答案

声明一个工具、要求模型调用它、验证那些参数:assess() 在没有循环的情况下,从一次单独的 pi-ai 调用拿到一个类型化的裁定。

一个应用从模型那里需要的大多数东西是一个问题和一份答案。assess.ts 就是那一级——第 1 层,模型/provider 访问,这架五级梯子的底层:一次请求,没有循环、没有会话、没有终端。一份工具声明是一个由模型填写的 schema,而 validateToolCall() 把答案变成一个类型化的值或一个异常,全部已观察于 Pi 1.0.4 上的脚本化响应之下。

运行它

使用 Pi 1.0.4 和示例仓库的测试运行器。下面的文件是本章的标准来源,被精确复现:

import {
	Type,
	validateToolCall,
	type Context,
	type Model,
	type Models,
	type Static,
	type Tool,
} from "@earendil-works/pi-ai";

// The result we want from the model. Everything downstream depends on this
// shape, not on the model's prose.
export const EvidenceAssessment = Type.Object({
	verdict: Type.Union([Type.Literal("supported"), Type.Literal("contradicted"), Type.Literal("insufficient")]),
	confidence: Type.Number({ minimum: 0, maximum: 1 }),
	citations: Type.Array(Type.String(), { description: "Evidence items relied on, quoted exactly." }),
	reason: Type.String({ description: "One or two sentences." }),
});
export type EvidenceAssessment = Static<typeof EvidenceAssessment>;

const submit: Tool = {
	name: "submit_assessment",
	description: "Submit your assessment of the claim. Call this exactly once.",
	parameters: EvidenceAssessment,
};

// One model call, no loop, no session. Input in, typed value out.
export async function assess(
	models: Models,
	model: Model<any>,
	claim: string,
	evidence: string[],
): Promise<EvidenceAssessment> {
	const context: Context = {
		systemPrompt: "Decide whether the evidence supports the claim. Use only the evidence given.",
		messages: [
			{
				role: "user",
				content: `Claim: ${claim}\n\nEvidence:\n${evidence.map((e, i) => `${i + 1}. ${e}`).join("\n")}`,
				timestamp: Date.now(),
			},
		],
		tools: [submit],
	};

	const reply = await models.complete(model, context);
	if (reply.stopReason === "error" || reply.stopReason === "aborted") {
		throw new Error(`model call failed: ${reply.errorMessage ?? reply.stopReason}`);
	}

	// toolChoice is only "auto" | "none", so the model is asked to call the tool,
	// not forced to. Check that it did.
	const call = reply.content.find((block) => block.type === "toolCall");
	if (!call) throw new Error("the model answered in prose instead of calling submit_assessment");

	// Throws if the arguments do not match the schema.
	return validateToolCall([submit], call) as EvidenceAssessment;
}

assess() 返回一个类型化的 EvidenceAssessment 或者抛出;fauxProvider() 驱动它,所以不需要密钥。

预期结果

assess.test.ts 的断言 会发生什么
合法的 submit_assessment 参数 一个类型化的 EvidenceAssessment;一次请求
破坏 schema 的参数 validateToolCall() 抛出;没有任何东西被传递下去
用散文而不是工具调用 抛出 …prose instead of calling submit_assessment
一次失败的请求 带着 provider 的消息抛出,绝不是一个静默的值

一次失败是一个带着 provider 消息的异常——测试里是 model call failed: 429 rate limited——而不是一个静默的值。

机制与局限

有文档记载:pi-ai README 与声明(1.0.4)定义了 Models 集合、complete()、包括 error 和 aborted 在内的 stopReason 值,以及 validateToolCall();toolChoice 只有 "auto" | "none"——模型是被请求调用该工具,从不被强迫。已观察:assess.test.ts 在 faux provider 上断言了上面全部四行(进程内运行时)。

这只是第 1 层那一级:一个智能体及其应用位于它之上。换成真实模型(builtinModels())是有文档记载、未运行的,因为它需要一个凭据;faux provider 证明的是管道,而不是一个真实模型多久调用一次该工具(第 41 章)。

完整源码与测试 。

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.