随着 OpenClaw 爆火,OpenClaw 背后的 pi-mono 可能会在以后被更多地提起。
PI 是一个用于构建 AI Agent(智能体)的工具包。它是一个包含多个相互叠加的包的 monorepo(单体仓库):
- • pi-ai 处理跨提供商的 LLM 通信
- • pi-agent-core 添加了带有工具调用功能的 Agent 循环
- • pi-coding-agent 为你提供一个完整的编程 Agent,包含内置工具、会话持久化和可扩展性
- • pi-tui 提供用于构建 CLI 界面的终端 UI
这些正是驱动 OpenClaw 的核心包。本指南将逐层介绍,逐步构建一个功能齐全、具有终端 UI、会话持久化和自定义工具的 Agent。
通过理解如何组合这些层,你可以按自己的方式构建生产级的 Agent 软件,而无需被锁定在特定的抽象中。
Pi 由 @badlogicgames 创建,它是一个开源的项目,github地址是:https://github.com/badlogic/pi-mono
文章很长,目录如下,可以选择查看:
- • 技术栈
- • 第 1 层:pi-ai
- • 第 2 层:pi-agent-core
- • 第 3 层:pi-coding-agent
- • 构建实用的东西 - 一个代码库助手
- • OpenClaw 为生产环境的适配
- • 进阶指引
下面是正文。
技术栈
通过分层的架构,在每一层增加新的能力,而且做了很好地隔离。
pi-ai - 通过一个接口调用任何 LLM。支持 Anthropic, OpenAI, Google, Bedrock, Mistral, Groq, xAI, OpenRouter, Ollama,以及国内的 MiniMax、智谱等。支持流式传输、补全、工具定义和成本跟踪。
pi-agent-core - 将 pi-ai 封装进一个 Agent 循环中。你定义工具,Agent 调用 LLM,执行工具,将结果反馈回去,并重复此过程直到完成。
pi-coding-agent - 完整的 Agent 运行时。内置文件工具(读取、写入、编辑、bash)、JSONL 会话持久化、上下文压缩(compaction)、技能(skills)和扩展系统。
pi-tui - 带有差量渲染(differential rendering)的终端 UI 库。支持 Markdown 显示、带自动补全的多行编辑器、加载旋转图标以及无闪烁的屏幕更新。
先决条件
- • Node.js 20+
- • 至少一个提供商的 API 密钥,对于国内的朋友可以使用智谱的GLM-5或Minimax M2.5等模型
示例代码以及说明
本文的所有代码已经开源到 github 是,仓库地址是:https://github.com/OmniTexts/pi-tutorial。所有的代码是使用 Minimax M2.5 作为后端 LLM,只需要在 .env 中配置相关的 API Key 即可。
或直接在环境变量中设置你的 API 密钥:
export MINIMAX_API_KEY=sk-api-...# orexport OPENAI_API_KEY=sk-...
第 1 层:pi-ai
第一次 LLM 调用
创建 basics.ts:
import { getModel, completeSimple } from"@mariozechner/pi-ai";asyncfunctionmain() {const model = getModel("minimax", "MiniMax-M2.5");const response = awaitcompleteSimple(model, { systemPrompt: "You are a helpful assistant.", messages: [ { role: "user", content: "中国的首都在哪里?", timestamp: Date.now() } ], });// response is an AssistantMessagefor (const block of response.content) { if (block.type === "text") { console.log(block.text); } }console.log(`\nTokens: ${response.usage.totalTokens}`);console.log(`Stop reason: ${response.stopReason}`);}main();
运行它:
npx tsx basics.ts
getModel 根据提供商和 ID 从 PI 内置的 2000 多个模型目录中查找模型。completeSimple 发送消息并在模型完成时返回完整的 AssistantMessage。
响应包含一个由类型化块(typed blocks)组成的 .content 数组——包括 text(文本)、thinking(思考)或 toolCall(工具调用)——以及用于计数的 .usage 和解释模型为何停止的 .stopReason(如 "stop", "toolUse", "length", "error", "aborted")。
流式传输 (Streaming)
completeSimple 会等待完整的响应。对于实时输出,请使用 streamSimple:
import { getModel, streamSimple } from"@mariozechner/pi-ai";asyncfunctionmain() {const model = getModel("minimax", "MiniMax-M2.5");const stream = streamSimple(model, { systemPrompt: "You are a helpful assistant.", messages: [ { role: "user", content: "用三句话解释 TCP/IP 的握手机制", timestamp: Date.now() } ], });forawait (const event of stream) { switch (event.type) { case"text_delta": process.stdout.write(event.delta); break; case"done": console.log(`\n\nTokens: ${event.message.usage.totalTokens}`); break; case"error": console.error("Error:", event.error.errorMessage); break; } }}main();
每个提供商都有自己的流格式——Anthropic、OpenAI 和 Google 的做法各不相同。
streamSimple 将它们标准化为一组统一的事件:start, text_start, text_delta, text_end, thinking_start/delta/end, toolcall_start/delta/end, done, 和 error。
我们只需要编写一次流处理程序,它就可以与任何提供商一起工作。对于大多数用例,你只关心 text_delta(文本块)和 done(最终消息)。
我们也可以直接等待最终消息:
const stream = streamSimple(model, context);const finalMessage = await stream.result(); // AssistantMessage
切换提供商
通过更改 getModel 调用即可切换到不同的提供商。其余代码保持不变。
// Just change this line - everything else stays the sameconst model = getModel("anthropic", "claude-opus-4-5");// const model = getModel("openai", "gpt-4o");// const model = getModel("google", "gemini-2.5-pro");// const model = getModel("groq", "llama-3.3-70b-versatile");const stream = streamSimple(model, context);
每个提供商需要在环境中设置自己的 API 密钥(ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, MINIMAX_API_KEY 等)。
你还可以为自托管端点定义自定义模型:
import type { Model } from"@mariozechner/pi-ai";constlocalModel: Model<"openai-completions"> = {id: "llama-3.1-8b",name: "llama-3.1-8b",api: "openai-completions",provider: "ollama",baseUrl: "http://localhost:11434/v1",reasoning: false,input: ["text"],cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },contextWindow: 128000,maxTokens: 8192,};
在底层,pi-ai 使用官方提供商 SDK(OpenAI SDK, Anthropic SDK 等)。api 字段决定哪个 SDK 处理请求——"openai-completions" 通过 OpenAI SDK 路由,这就是为什么它可以与任何兼容 OpenAI 的端点(Ollama, vLLM, Mistral 等)一起工作。
API 密钥会根据提供商名称(OPENAI_API_KEY, ANTHROPIC_API_KEY 等)从环境变量中自动解析并传递给 SDK,SDK 会处理身份验证。Ollama 不需要身份验证,所以上面的例子可以直接运行。对于需要密钥的提供商,可以设置匹配的环境变量或直接传递密钥:
const stream = streamSimple(localModel, context, { apiKey: "your-api-key",});
思考层级 (Thinking levels)
PI 支持扩展思考(extended thinking)的模型(如 Claude, o3, Gemini 2.5 等)可以通过 reasoning 选项启用。默认情况下是关闭的。
const stream = streamSimple(model, context, { reasoning: "high", // "minimal" | "low" | "medium" | "high" | "xhigh"});
启用后,流会在发出 text_delta 的同时发出 thinking_delta 事件。
第 2 层:pi-agent-core
pi-ai 让你能够与 LLM 对话。pi-agent-core 让 LLM 能够通过工具进行回应。
Agent 类运行标准的 Agent 循环:向 LLM 发送消息,执行它调用的任何工具,反馈结果,重复直到模型停止。
定义工具
工具使用 TypeBox[1] 模式(schemas)进行类型安全的参数定义:
import { Type } from"@mariozechner/pi-ai";importtype { AgentTool } from"@mariozechner/pi-agent-core";const weatherParams = Type.Object({city: Type.String({ description: "City name" }),});constweatherTool: AgentTool<typeof weatherParams> = {name: "get_weather",label: "Weather",description: "Get the current weather for a city",parameters: weatherParams,execute: async (toolCallId, params, signal, onUpdate) => { // params is typed: { city: string } const temp = Math.round(Math.random() * 30); return { content: [{ type: "text", text: `${params.city}: ${temp}C, partly cloudy` }], details: { temp, city: params.city }, }; },};
将模式定义为独立变量,并将其作为泛型参数传递给 AgentTool<typeof schema> —— 这为 TypeScript 提供了在 execute 内部正确推断 params 所需的类型信息。
每个工具都有:
- • name - LLM 用来调用它的标识符
- • label - 人类可读的显示名称
- • description - 告诉 LLM 何时以及如何使用该工具
- • parameters - TypeBox 模式;在执行前使用 AJV 进行验证
- • execute - 当 LLM 调用工具时运行;返回
content(发送回 LLM)和details(用于你的 UI,不发送给 LLM)
onUpdate 回调允许你在执行期间流式传输部分结果——这对于运行时间较长的工具(如 bash 命令)非常有用。
创建 Agent
将上面的天气工具与模型和流式传输函数连接起来。我们将在接下来的部分中添加事件处理、提示词和完整的工作示例。
import { Agent } from"@mariozechner/pi-agent-core";import { getModel, streamSimple } from"@mariozechner/pi-ai";const model = getModel("minimax", "MiniMax-M2.5");const agent = newAgent({initialState: { systemPrompt: "You are a helpful assistant with access to tools.", model, tools: [weatherTool], thinkingLevel: "off", },streamFn: streamSimple,});
Agent 接受一个 initialState(系统提示词、模型、工具、思考层级)和一个 streamFn —— 实际调用 LLM 的函数。从 pi-ai 传入 streamSimple 会将 Agent 连接到模型指定的任何提供商。
事件流
订阅事件以查看 Agent 正在做什么:
agent.subscribe((event) => {switch (event.type) { case"agent_start": console.log("Agent started"); break; case"message_update": // Streaming text from the LLM if (event.assistantMessageEvent.type === "text_delta") { process.stdout.write(event.assistantMessageEvent.delta); } break; case"tool_execution_start": console.log(`\nTool: ${event.toolName}(${JSON.stringify(event.args)})`); break; case"tool_execution_end": console.log(`Result: ${event.isError ? "ERROR" : "OK"}`); break; case"agent_end": console.log("\nAgent finished"); break; }});
完整事件列表:
agent_startagent_endturn_startturn_endmessage_startmessage_updatemessage_endtool_execution_starttool_execution_updatetool_execution_end
运行 Agent
await agent.prompt("What's the weather in Tokyo and London?");
就是这样。Agent 会:
-
- 将你的消息发送给 LLM
-
- LLM 决定为东京调用
get_weather
- LLM 决定为东京调用
-
- Agent 执行工具,反馈结果
-
- LLM 为伦敦调用
get_weather
- LLM 为伦敦调用
-
- Agent 再次执行,反馈结果
-
- LLM 生成最终的文本回复
你不需要编写循环。Agent 会处理它。
完整示例
这是一个包含两个工具(list_files、read_file)的完整工作 Agent:
import { Agent } from"@mariozechner/pi-agent-core";import { getModel, streamSimple } from"@mariozechner/pi-ai";import { Type } from"@mariozechner/pi-ai";importtype { AgentTool } from"@mariozechner/pi-agent-core";import * as fs from"fs";const readFileParams = Type.Object({path: Type.String({ description: "Path to the file" }),});constreadFileTool: AgentTool<typeof readFileParams> = {name: "read_file",label: "Read File",description: "Read the contents of a file",parameters: readFileParams,execute: async (_id, params) => { try { const content = fs.readFileSync(params.path, "utf-8"); return { content: [{ type: "text", text: content }], details: {}, }; } catch (err: any) { return { content: [{ type: "text", text: `Error: ${err.message}` }], details: {}, }; } },};const listFilesParams = Type.Object({path: Type.String({ description: "Directory path", default: "." }),});constlistFilesTool: AgentTool<typeof listFilesParams> = {name: "list_files",label: "List Files",description: "List files in a directory",parameters: listFilesParams,execute: async (_id, params) => { const files = fs.readdirSync(params.path); return { content: [{ type: "text", text: files.join("\n") }], details: { count: files.length }, }; },};asyncfunctionmain() {const model = getModel("minimax", "MiniMax-M2.5");const agent = newAgent({ initialState: { systemPrompt: "You can read files and list directories. Be concise.", model, tools: [readFileTool, listFilesTool], thinkingLevel: "off", }, streamFn: streamSimple, }); agent.subscribe((event) => { if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { process.stdout.write(event.assistantMessageEvent.delta); } if (event.type === "tool_execution_start") { console.log(`\n[${event.toolName}] ${JSON.stringify(event.args)}`); } });clauawait agent.prompt("What files are in the current directory? Read the package.json if it exists.");console.log();}main();
引导 (Steering) 与跟进 (Follow-ups)
如果 Agent 正在运行,你想重定向它:
// Interrupt: delivered after the current tool finishes.// Remaining pending tools are skipped.agent.steer({role: "user",content: "Actually, skip that and read tsconfig.json instead.",timestamp: Date.now(),});// Follow-up: queued for after the agent finishes naturally.// Doesn't interrupt current work.agent.followUp({role: "user",content: "Now summarize what you found.",timestamp: Date.now(),});
steer 会中断 —— 它跳过剩余的工具并注入你的消息。followUp 会等待 —— 它将消息排队,等待 Agent 自然停止后处理。OpenClaw 使用引导来处理实时用户消息(当 Agent 工作时有人打字),并使用跟进进行程序化链接。
状态管理
你可以随时更改 Agent 的配置:
agent.setModel(getModel("openai", "gpt-4o")); // Switch providers mid-sessionagent.setThinkingLevel("high"); // Enable extended thinkingagent.setSystemPrompt("New instructions."); // Update the system promptagent.setTools([...newTools]); // Swap the tool setagent.replaceMessages(trimmedMessages); // Replace conversation history
Agent 会在下一轮次应用这些更改。
第 3 层:pi-coding-agent
pi-agent-core 提供了循环。pi-coding-agent 则提供了一个生产就绪的 Agent,具备内置工具、会话持久化和可扩展性。它建立在 pi-agent-core 之上 —— 当你使用 pi-coding-agent 时,你在底层已经使用了 pi-agent-core。
大多数用户应该从这里开始,只有在需要不使用内置编程工具或会话系统的自定义 Agent 时,才直接使用 pi-agent-core。
内置工具
pi-coding-agent 有 7 个内置工具。默认情况下有 4 个处于激活状态 (codingTools),另外 3 个可用但默认关闭:
默认工具(激活):
| 工具 | 作用 |
|---|---|
read |
读取文件内容和图片(jpg、png、gif、webp)。图片将作为附件返回。文本输出会被截断为 2000 行或 50KB。支持通过 offset/limit 分页读取大文件。 |
bash |
在工作目录执行 shell 命令。返回标准输出和标准错误,并会被截断为最后 2000 行或 50KB。提供可选的 timeout (超时时间,单位为秒)。 |
edit |
替换文件中的精确文本。oldText 必须完全匹配(包括空格)。用于精确的、外科手术般的修改。 |
write |
将内容写入文件。如果文件不存在则自动创建,如果已存在则覆盖。自动创建父级目录。 |
附加工具(可选):
| 工具 | 作用 |
|---|---|
grep |
使用正则表达式或字面量模式在文件内容中搜索。返回匹配的行、文件路径和行号。遵循 .gitignore 规则。底层使用 ripgrep。 |
find |
使用 glob 模式查找文件。返回相对于搜索目录的匹配路径。遵循 .gitignore 规则。 |
ls |
列出目录内容。条目按字母顺序排列,目录带有 / 后缀。包含隐藏文件(dotfiles)。 |
这些工具被组织成预设:
import { codingTools, readOnlyTools } from "@mariozechner/pi-coding-agent";codingTools; // [read, bash, edit, write] - defaultreadOnlyTools; // [read, grep, find, ls] - exploration without modification
或者选择单个工具:
import { allBuiltInTools } from "@mariozechner/pi-coding-agent";// allBuiltInTools.read, allBuiltInTools.bash, allBuiltInTools.edit,// allBuiltInTools.write, allBuiltInTools.grep, allBuiltInTools.find, allBuiltInTools.lsconst { session } = await createAgentSession({ model, tools: [allBuiltInTools.read, allBuiltInTools.bash, allBuiltInTools.grep], sessionManager: SessionManager.inMemory(),});
createAgentSession
createAgentSession 将所有东西连接在一起 —— 模型、工具、会话持久化、设置:
import { createAgentSession, SessionManager } from"@mariozechner/pi-coding-agent";import { getModel, streamSimple } from"@mariozechner/pi-ai";asyncfunctionmain() {const model = getModel("minimax", "MiniMax-M2.5");const { session } = awaitcreateAgentSession({ model, thinkingLevel: "off", sessionManager: SessionManager.inMemory(), }); session.agent.streamFn = streamSimple; session.subscribe((event) => { if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { process.stdout.write(event.assistantMessageEvent.delta); } if (event.type === "tool_execution_start") { console.log(`\n[${event.toolName}]`); } });await session.prompt("What files are in the current directory? Summarize the package.json.");console.log(); session.dispose();}main();
这是一个可工作的编程 Agent。它可以读取你的文件,运行命令,编辑代码,以及写入新文件。SessionManager.inMemory() 意味着会话存在于内存中,并在进程退出时消失。
会话持久化
为了持久化会话,请将 SessionManager 指向一个文件:
import * as path from "path";const sessionFile = path.join(process.cwd(), ".sessions", "my-session.jsonl");const sessionManager = SessionManager.open(sessionFile);const { session } = await createAgentSession({ model, sessionManager,});
会话存储为 JSONL[2] 文件,具有树状结构 —— 每个条目都有一个 id 和 parentId。这使得分支成为可能:你可以导航到对话中的任何先前点并从那里继续,而不会丢失历史记录。
SessionManager 有几个静态工厂方法。根据你的用例选择一个并将其传递给 createAgentSession:
// Option 1: In-memory (ephemeral, nothing written to disk)const sessionManager = SessionManager.inMemory();// Option 2: New persistent session in ~/.pi/agent/sessions/const sessionManager = SessionManager.create(process.cwd());// Option 3: Open a specific session fileconst sessionManager = SessionManager.open("/path/to/session.jsonl");// Option 4: Continue the most recent session (or create new if none exists)const sessionManager = SessionManager.continueRecent(process.cwd());// Then pass whichever on…