Lesson 01

Agent Loop 核心循环

整个 AI 编程 Agent 的秘密就在一个 while 循环里

// Architecture Diagram

WHILE LOOP: stopReason == "tool_use" tool_use tool_result → messages.append() stop_reason != "tool_use" User Input 用户输入 LLM Claude API Tool Execute 工具执行 Output 输出结果 01 02 03

Key Concepts 核心概念

01

核心模式 Core Pattern

整个 Agent 的核心就是 while(stopReason == "tool_use")。循环条件由模型的返回值决定,不是硬编码的。

The entire agent is driven by a single while loop. The loop condition is determined by the model's stop_reason, not hardcoded logic.

02

三步循环 Three-Step Loop

每一轮循环只做三件事:发送消息给模型 → 执行模型要求的工具 → 把结果塞回对话历史。

Each iteration: send messages to API, execute requested tool, append tool_result back to conversation history.

03

模型即 Agent

循环本身只是"传话员"。真正做决策的是模型——它决定用什么工具、何时停止。Agent 代码不做任何决策。

The loop is just a messenger. The model decides which tools to call and when to stop. Zero decision logic in the agent code.

试一试 Try It Out

1

创建一个输出问候消息的 Java 文件

Create a Java file that outputs a greeting message

2

列出当前目录下的 Java 文件

Enumerate Java files in the current directory

3

识别当前活跃的 git 分支

Identify the active git branch

4

创建一个新目录,并在其中生成多个文件

Generate a new directory with multiple files inside it