Agent Loop 引擎 — agent-loop.tsAgent Loop Engine — agent-loop.ts

pi-agent-core · 695 行 · 整个 Agent 框架的核心循环pi-agent-core · 695 lines · The core loop of the entire Agent framework

这是整个 Agent 的"心脏"——一个 while 循环不断重复:把对话历史发给 LLM,检查 LLM 是否要调用工具,如果要就执行工具并把结果塞回对话,然后再问 LLM 下一步。所有 AI Agent 产品的核心都是这个循环。 This is the "heart" of the entire Agent — a while loop that repeats endlessly: send conversation history to the LLM, check if the LLM wants to call tools, execute the tools if so and feed results back into the conversation, then ask the LLM for the next step. Every AI Agent product is built around this loop.

这一章分为上下两篇:This chapter is split into two parts:

上篇Part A 源码精读Source Code Deep Read

左边是 agent-loop.ts 的完整原始代码,右边是逐段中文解读和生活类比。695 行代码从第一行读到最后一行,每个关键设计都标注了"为什么这样写"。

Left column: the full original code of agent-loop.ts. Right column: line-by-line explanations with real-life analogies. All 695 lines from first to last, with every key design decision annotated with "why it's done this way."

适合第一遍精读,搞懂每一行在做什么。

Best for your first close reading — understand what every line does.

开始阅读 →Start Reading →
下篇Part B 中文翻译版Module Overview

用中文伪代码重述核心循环的整体结构,把上篇读到的细节串成一条线:双层 while 循环是怎么嵌套的、消息变换管道怎么工作、工具执行的完整流程。附 5 条"带走认知"。

Restates the core loop's overall structure in pseudocode, connecting the details from Part A into a single thread: how the dual while-loops nest, how the message transform pipeline works, the complete tool execution flow. Includes 5 key takeaways.

已优化排版,支持直接 Ctrl+P 打印 / 保存 PDF。读完上篇后用它梳理全局逻辑,打印出来随时翻阅。

Print-optimized layout (Ctrl+P / Save as PDF). Use it after Part A to consolidate the big picture — print it out for quick reference anytime.

开始阅读 →Start Reading →
推荐顺序:先读上篇(源码精读),再读下篇(中文翻译版)。上篇搞懂每行代码,下篇把零散的理解串成完整画面。
时间有限?直接从下篇入手也可以,它能让你快速抓住核心循环的全局结构。
Recommended order: Read Part A (Source Code Deep Read) first, then Part B (Module Overview). Part A helps you understand each line; Part B connects the pieces into a complete picture.
Short on time? Start with Part B — it gives you the big picture of the core loop's structure quickly.