Example

用一个语料库工具单独运行智能体循环

pi-agent-core 的 Agent 先运行工具再回答,把两者都记进转录记录,并把一次未命中当作数据:接受测试的 research-agent.ts。

research-agent.ts 用一个读语料库的工具和一个注入的流函数,包裹了 pi-agent-core 的 Agent——也就是编码智能体所构建的那个类:这是第 2 层,智能体内核,编码智能体的会话、信任门、扩展和终端都不在场。与第 1 章那个自包含的打印脚本不同,这是一个库函数:语料库、模型和流函数都来自调用者,而转录记录是你断言的数据。下面的一切都是已观察于 Pi 1.0.4 上的脚本化响应之下。

运行它

下面的文件是本章的标准来源,被精确复现;它不是独立可运行的。research-agent.test.ts 把 provider 脚本化并断言转录记录——请在示例仓库的测试运行器上、Pi 1.0.4 上运行它。

import { Agent, type AgentTool } from "@earendil-works/pi-agent-core";
import { Type, type Model, type Models } from "@earendil-works/pi-ai";

export interface Corpus {
	[id: string]: string;
}

// A tool is data plus one function. This one is read-only and pure, so it is
// safe to run in parallel with itself.
const LookupParams = Type.Object({ query: Type.String() });

export function lookupEvidence(corpus: Corpus): AgentTool<typeof LookupParams> {
	return {
		name: "lookup_evidence",
		label: "Look up evidence",
		description: "Return the corpus entries whose text contains the query. Use short keywords.",
		parameters: LookupParams,
		async execute(_id, params) {
			const q = params.query.toLowerCase();
			const hits = Object.entries(corpus).filter(([, text]) => text.toLowerCase().includes(q));
			const text = hits.length ? hits.map(([id, t]) => `[${id}] ${t}`).join("\n") : "no matches";
			return { content: [{ type: "text", text }], details: { query: params.query, hits: hits.map(([id]) => id) } };
		},
	};
}

// The agent core takes exactly two things from the outside: a model and a
// stream function. The prompt, the tools and the transcript are ours.
export function makeResearchAgent(models: Models, model: Model<any>, corpus: Corpus): Agent {
	return new Agent({
		initialState: {
			systemPrompt: "Research the claim using lookup_evidence. Answer in one sentence.",
			model,
			tools: [lookupEvidence(corpus)],
		},
		streamFn: models.streamSimple.bind(models),
	});
}

预期结果

research-agent.test.ts 的断言 循环做了什么
循环先运行工具再回答 转录记录的角色是 ["user", "assistant", "toolResult", "assistant"];provider 被调用了两次,每轮一个请求
事件按顺序触发 tool_execution_start 在 tool_execution_end 之前;最后一个事件是 agent_end
一个什么都没找到的工具 lookup_evidence 返回 "no matches",带 isError: false——是数据,不是失败

在裸内核里,agent_end 真的就是终点——agent_settled 和 agent_before_settle 不在内核的类型里;它们属于编码智能体在运行之后的额外工作。

机制与局限

有文档记载:Agent 构造函数选项、streamFn、作为 Tool 之扩展的 AgentTool(其 execute() 接收已经验证过的 params)、抛出即失败(一个抛出的 execute 变成一个带 isError: true 的工具结果)、默认并行执行工具,以及那两个声明的运行时依赖(pi-agent-core README 与声明,1.0.4)。已观察:research-agent.test.ts 在脚本化响应下断言了转录记录形状、请求次数,以及未命中即数据这条规则;agent_settled 不在内核的类型里,这是对声明的一次阅读,而不是一次运行时观察。

给 agent.state.messages 赋值在这里是权威的,上面没有会反对的会话——在编码智能体内部,SessionManager 拥有那个副本(第 34 章,已观察)。这个工具是只读且纯粹的,所以没有任何东西守护它:executionMode: "sequential" 和第 39 章的钩子没有展示,而脚本化的 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.