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:
左边是 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.
用中文伪代码重述核心循环的整体结构,把上篇读到的细节串成一条线:双层 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.