本页目录

📘 第 4 课:The agent loop explained(智能体循环详解)

所属课程:the AI Platform 101(课程 003) 官方课时定位:Section 2「Teaching your Agent」— Lesson 4 / 共 12 课时 ID:486254 | 官方地址:https://anthropic.skilljar.com/claude-platform-101/486254 形式:Video(视频课 + 文稿) 针对认证:CCAR-P(架构师 Professional) 整理日期:2026-10-14 ⚠️ 语料来源:官方 Skilljar 课程正文(用户提供,需登录)。CC BY-NC-SA 4.0,仅供个人学习。 ⭐⭐ 本课权重提示:全课技术心脏。Section 2 从这里开始,后面 8 节课(tool use / thinking / 内置工具 / Skills / MCP / 上下文管理 / 托管智能体)全部是往这个循环上加东西。本课的三句官方论断(尤其是「你拥有循环与工具,AI 拥有推理」)直接命中领域 1(17%)与领域 3(19%)。


🎯 本课学习目标

⚠️ 本课官方未提供 What you'll learn 区块。以下按文稿结构反推:

  1. 能说清一次调用与一个智能体的差别在哪里。
  2. 能背出智能体的官方定义(尤其是 without a human in the middle)。
  3. 能写出/读懂五步循环与 while True 的最小实现。
  4. ⭐⭐ 能解释 stop_reason 的两种取值(end_turn / tool_use)如何驱动循环。
  5. ⭐ 能说清 tool_result 的配对方式(tool_use_id)与放回哪个 role。
  6. ⭐⭐ 能背出责任划分那句:You own the loop and the tools. the AI owns the reasoning.

📖 一、视频导读

官方原句: You've made API calls, but a single call only returns one response. If you want to automate a workflow, the AI needs to act, look at the result, decide what's next, and keep going. That pattern is what people mean when they talk about agentic workflows.

精译:你已经会发 API 调用了,但一次调用只返回一个响应。如果你想让一个工作流自动化,AI 就需要行动、看结果、决定下一步、然后继续。这个模式,就是人们说「智能体工作流(agentic workflows)」时所指的东西。

⭐ 本课的分界线: | | 第 1–3 课 | 第 4 课起 | |---|---|---| | 形态 | 一次调用 → 一次响应 | 循环:调用 → 工具 → 结果 → 再调用 | | 谁决定下一步 | 你的代码(一次性) | ⭐ AI 决定,直到它认为做完 | | 考纲对应 | augmented LLM | ⭐ agentic |

这正好对应 CCAR-P 领域 1 的架构模式三分:workflow(预定义编排)/ agentic(自主)/ augmented LLM(增强)。本课就是从 augmented 跨到 agentic 的那一课。


🤖 二、⭐ 智能体到底是什么(What an agent actually is)

官方原句: An agent is an autonomous version of the AI, running both sides of the messaging loop without a human in the middle.* An agent receives a task, picks a tool, and executes code in a loop until the AI decides the task is done*.

精译: 智能体是 AI 的自主形态,它同时跑着消息循环的两侧,中间没有人。 一个智能体接收一个任务、挑选一个工具、并在循环中执行代码,直到 AI 认为任务完成。

⭐ 定义里的三个要件(拆开背)

要件 官方原句 中文 为什么重要
① 自主 an autonomous version of the AI AI 的自主形态 不是脚本驱动,是它自己推进
② ⭐ 两侧都它跑 running both sides of the messaging loop 消息循环的两侧都由它跑 ⭐ 用户侧与助手侧都被程序接管
③ ⭐⭐ 中间没有人 without a human in the middle 中间没有人 ⭐ 这是「智能体」区别于「人机对话」的判据

⭐⭐ without a human in the middle 是本课最可能被考的短语。 考点:题干问「什么使一个系统成为 agentic 而不是 augmented」→ 正解涉及循环由程序驱动、无需人在每一步确认。 呼应课程 002:002 讲 Agency 模式时说 AI operates with latitude inside boundaries you set —— 本课给出了它的实现形态:循环自动化 = latitude;你写的 tools 数组与 run_tool 的实现 = boundaries。 ⚠️ 注意:「中间没有人」不等于「没有人类监督」—— 002 的 Diligence 与 HITL 依然成立,只是不在每一步**。

五步循环(官方编号,原样保留顺序)

官方原句:The easiest way to implement an agent loop looks like this:

步 官方原句 中文
1 Send a message to the AI with tools available. 发消息给 AI,带上可用工具
2 the AI responds with either a final answer or a request to use a tool you defined. AI 回应要么一个最终答案,要么一个「使用你定义的某个工具」的请求
3 Your code executes that tool. ⭐ 你的代码执行那个工具
4 You send the result back to the AI. ⭐ 你把结果发回给 AI
5 Repeat until the stop reason is end_turn. ⭐ 重复,直到 stop reason 为 end_turn

⭐⭐ 第 2 步的「二分」是循环的枢纽:AI 每次响应只有两种可能——给最终答案,或请求用工具。这直接映射到 stop_reason 的两个取值。 ⭐⭐ 第 3 步与第 4 步是「你的代码」做的,不是 AI 做的 —— 这是后面那句责任划分的技术根据。

官方的比喻

Think of it as a conversation where the turns alternate: the user kicks things off, the agent calls a tool, the tool returns a result, and the agent keeps going until it has an answer.

精译:把它想成一场回合交替的对话:用户起头,智能体调用工具,工具返回结果,智能体继续,直到它有了答案。

⚠️ 官方两处「循环动词」顺序不一致(记录备查)

出处 官方原句 顺序
课程页 About how the AI acts, observes, and decides** act → observe → decide
本课 Recap An agent is the AI in a loop: observe, decide, act, repeat** observe → decide → act → repeat

⭐ 考试口径建议:若题目考「循环的四步口诀」,用 Recap 的 observe, decide, act, repeat(观察 → 决策 → 行动 → 重复) —— 它是本课的定稿总结,且带 repeat,更完整。 若只考「AI 在循环里做什么」三件事,两者是同一组动词,不构成矛盾。


💻 三、最小可运行示例(A minimal working example)

官方原句:To see this loop run end to end without dragging in a database or a UI, we'll wire up a fake tool called get_weather and ask the AI what to wear in Austin today. the AI has no way to know the weather on its own, so it has to call the tool, read the result, and then give you an answer.

精译:为了让这个循环端到端跑起来,又不拖进数据库或界面,我们来接一个叫 get_weather 的假工具,然后问 AI 今天在奥斯汀该穿什么。AI 自己没有办法知道天气,所以它必须调用工具、读取结果,然后才能给你答案。

⭐ the AI has no way to know the weather on its own —— 官方用这个例子证明了工具的必要性:模型的知识止于训练数据,实时信息必须靠工具。这与考纲领域 5 的 knowledge cutoff(知识截止)是同一件事的两个说法。

官方代码(保持原样)

import anthropic

client = anthropic.the AI provider()

# The tools array tells the AI what's available:
# a name, a description, and a JSON schema for the inputs.
tools = [
    {
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "The city to get weather for",
                }
            },
            "required": ["city"],
        },
    }
]

# run_tool is just a hardcoded lookup.
# In a real app, this would hit your database, an API, whatever.
def run_tool(name, tool_input):
    if name == "get_weather":
        return f"Weather in {tool_input['city']}: 95F, sunny"
    raise ValueError(f"Unknown tool: {name}")

messages = [
    {"role": "user", "content": "What should I wear in Austin today?"}
]

# The agent loop. Each iteration sends messages to the AI
# and switches on the response's stop reason.
while True:
    response = client.messages.create(
        model="current-model-fast",
        max_tokens=1024,
        tools=tools,
        messages=messages,
    )

    if response.stop_reason == "end_turn":
        # the AI is done. Print the final text and break.
        for block in response.content:
            if block.type == "text":
                print(block.text)
        break

    if response.stop_reason == "tool_use":
        # Find the tool use blocks in the response and run each one.
        tool_results = []
        for block in response.content:
            if block.type == "tool_use":
                result = run_tool(block.name, block.input)
                tool_results.append(
                    {
                        "type": "tool_result",
                        "tool_use_id": block.id,
                        "content": result,
                    }
                )

        # Push the assistant's response and our tool results
        # back into messages, then loop again so the AI can answer.
        messages.append({"role": "assistant", "content": response.content})
        messages.append({"role": "user", "content": tool_results})

⚠️ 抓取件说明:anthropic.the AI provider() 与 model="current-model-fast" 为替换残留;按第 3 课的映射,current-model-fast 对应 Sonnet 档(current-model-lite = Haiku,current-model = Opus)。不要背这些字符串。

⭐ 官方点名的「三个要点」(Three pieces to notice)

① tools 数组的三要素

The tools array tells the AI what's available: a name, a description, and a JSON schema for the inputs.

要素 作用 本课取值
name 工具名 get_weather
description ⭐ 告诉 AI 这是什么、何时用 Get the current weather for a city.
input_schema ⭐ JSON Schema,声明入参 city(string,required)

⭐⭐ description 又一次成为关键 —— 呼应课程 002 第 2 课的考点:Skill/工具能否被正确命中,取决于 description 的语义覆盖度。在平台层,这个字段就是触发判据。 ⭐ input_schema 的 required: ["city"] —— 声明必填参数,这是 schema 的约束作用。

② run_tool 是你的地盘

run_tool is just a hardcoded lookup.* In a real app, this would hit your database, an API, whatever*.

精译:run_tool 只是一个硬编码的查询。 在真实应用里,它会去打你的数据库、某个 API,或者随便什么。

⭐⭐ 这是「你拥有工具」的技术根据:工具的执行体是你写的函数,AI 只产出「想调用什么、传什么参数」(block.name / block.input)。 安全含义(领域 5 / 领域 3):攻击面在你写的 run_tool 里,不在模型里。最小特权、capability bloat 的落点就在这里 —— 工具集必须裁剪(呼应第 1 课「工具与权限决定它能做什么」)。

③ ⭐⭐ 循环本体:按 stop_reason 分流

The loop is the agent loop. Each iteration sends the messages to the AI and switches on the response's stop reason. On end_turn, the AI is done — print the final text and break. On tool_use, find the tool use blocks, run each one, push the assistant's response and your tool results back into messages, and loop again so the AI can answer.

stop_reason 含义 代码动作
⭐ tool_use AI 想用工具 找 tool_use block → run_tool → 组装 tool_result → 追加回 messages → 继续循环
⭐ end_turn AI 认为做完了 打印最终 text → break

⭐⭐ 三个极易考的实现细节

① tool_result 必须靠 tool_use_id 配对

{"type": "tool_result", "tool_use_id": block.id, "content": result}

⭐ tool_use_id 取自 block.id —— 一次响应可能有多个 tool_use block,没有 id 就无法把结果对回请求。考点:并行工具调用场景下,id 配对是唯一正确的归位方式。

② ⭐ 工具结果放进的是 user role(反直觉,必记)

messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})

⭐⭐ tool_result 被放在 user 角色的消息里 —— 这是官方写法,极易记错成 assistant 或 tool。 记忆锚:助手的请求(assistant,整段 content)→ 你的执行结果(user,tool_results)。 ⚠️ 注意第一行追加的是 整个 response.content(不是只追加 tool_use block),保持上下文完整。

③ 一次循环 = 多次 API 调用

⭐ 循环里每次 while 迭代都会发一次 messages.create —— 一次智能体任务 ≠ 一次 API 请求。这直接关系到成本与 token 计量(呼应第 3 课 response.usage):循环是成本的放大器,也是第 10 课 Context management 存在的原因。


▶️ 四、跑起来看(Running it)

官方原句:When you run the script, you'll see two turns: 1. Turn one: the stop reason is tool_use.* the AI requests get_weather for Austin, and your code returns the temperature and conditions. 2. Turn two: the stop reason is end_turn, and the AI tells you to wear something light and breathable. Two API calls, one tool execution, one final answer. That's the entire loop.***

轮次 stop_reason 发生了什么
Turn 1 tool_use AI 请求 get_weather(Austin);你的代码返回温度与天气状况
Turn 2 end_turn AI 给出最终答案:穿轻薄透气的

⭐⭐ 最小完整形态 = Two API calls, one tool execution, one final answer(两次 API 调用、一次工具执行、一个最终答案)。 这个「2-1-1」是智能体循环的最小计数,很适合出「共发了几次请求」的计算型题目。

⭐ Everything you build with the the AI API is going to be similar to this. (你用这个 API 构建的一切,都会和这个相似。)—— 官方明说:这是全平台的通用形状。


🏭 五、⭐ 生产里的同一个循环(The same loop in production)

官方原句: In a real environment, this same loop powers something like an auto-review endpoint: a compliance agent that reads a structural report, looks up the relevant building codes via a tool, and writes risk findings back to the database one by one as it works. The shape of the loop is identical to what you just ran. The differences are: * Real tools instead of a mock weather lookup. * Results stream back to the UI as server-sent events. * Findings get persisted to a risk-finding table.**

精译:在真实环境里,同是这个循环驱动着类似自动审查接口这样的东西:一个合规智能体,它读取一份结构报告、通过工具查相关的建筑规范,并在工作过程中把风险发现一条条写回数据库。 这个循环的形状和你刚才跑的完全一样。 差别在于: * 真实的工具,而不是一个模拟的天气查询。 * 结果以 server-sent events 的形式流回界面。 * 发现被持久化到一张风险发现表里。

⭐ 演示 vs 生产:三项差异(其余完全相同)

维度 演示(weather) 生产(compliance)
工具 mock weather lookup Real tools
回传 print ⭐ server-sent events(SSE)流式回传 UI
持久化 无 ⭐ persisted to a risk-finding table

⭐⭐ The shape of the loop is identical(循环的形状完全一致) —— 与第 2 课的 It's the same call — just wrapped in a route handler、第 3 课的 The eval is the same shape every single time 构成官方的第三个「形状不变」论断。 这三句话是同一条方法论:平台学习是一次性的 —— 学会一个形状,然后只换工具与管路。 记忆锚:形状不变,工具与管路在换。

⭐ one by one as it works(边工作边一条条写)—— 智能体在工作过程中持续落库,不是结束后一次性写。这对应增量持久化与可恢复性,也是可观测性的落点(领域 3)。 ⭐ server-sent events(SSE)是流式回传的标准手段 —— 呼应第 12 课的 event stream。


🔑 六、核心要点(Recap)· 官方五条

  1. An agent is the AI in a loop: observe, decide, act, repeat. 智能体就是循环中的 AI:观察、决策、行动、重复。
  2. The loop is simple: send messages with tools, run any tool the AI requests, feed the result back, and stop when the stop reason is end_turn. 循环很简单:带上工具发消息,运行 AI 请求的任何工具,把结果喂回去,并在 stop reason 为 end_turn 时停下。
  3. ⭐⭐ You own the loop and the tools. the AI owns the reasoning. 你拥有循环与工具。AI 拥有推理。
  4. The same loop shape scales from a mock weather demo to a production compliance agent — only the tools and plumbing change. 同一个循环形状可以从一个模拟天气 demo 一路扩展到生产级合规智能体 —— 只有工具与管路在变。
  5. When you don't want to own the loop, managed agents run this exact loop for you on the AI provider's infrastructure. 当你不想自己拥有这个循环时,托管智能体会在平台基础设施上替你跑这个一模一样的循环。

⭐⭐ 第 3 条:全课最重要的责任划分

You own the loop and the tools. the AI owns the reasoning.

你拥有 AI 拥有
⭐ the loop(循环:何时继续、何时停) ⭐ the reasoning(推理:用什么工具、传什么参数、够不够)
⭐ the tools(工具集与它们的实现)
→ while True / break / run_tool / tools 数组 → stop_reason / block.name / block.input

⭐⭐ 这一句把课程 002 的抽象原则落成了代码边界: * 002 说 Delegation(委派)—— 本课告诉你委派的是什么:推理;不委派的是什么:循环控制权与工具实现权。 * 002 说 Agency 的两个限定(latitude + inside boundaries you set)—— 本课的 latitude = AI 决定调哪个工具、何时停;boundaries = 你给的 tools 数组与你写的 run_tool。 * 002 说 You own the outcome, not the output —— 本课的对应物:你拥有循环与工具,所以产出出问题时,根因在你这一侧的配置,不在推理。

记忆锚:循环和工具是你的,推理是它的。出事先看你的工具集。

第 5 条:前向钩子

managed agents 在第 11–12 课展开。官方在此先给出判据:「当你不想拥有这个循环时」 —— 这是一个成本/控制权的权衡,不是能力问题。


🧠 本课 → CCAR-P 考点映射

本课知识点 命中考纲条目 领域
⭐⭐ without a human in the middle;循环自动化判据 选择架构模式(workflow / agentic / augmented LLM) 领域 1(17%)
⭐⭐ You own the loop and the tools. the AI owns the reasoning. 复杂问题分解;责任与控制权边界 领域 1
⭐⭐ tools 数组三要素(name / description / input_schema) 工具/智能体配置;能力膨胀(capability bloat) 领域 3(19%)
⭐ run_tool 由你实现 → 攻击面在你这侧 分析认证与授权需求、识别安全缺口;最小特权 领域 3 + 领域 5(14%)
⭐ stop_reason(tool_use / end_turn)驱动循环 集成实现与响应解析 领域 3
⭐ tool_result + tool_use_id 配对;结果放 user role 集成协议正确性 领域 3
⭐ 一次循环 = 多次 API 调用 → 成本放大 权衡准确率与延迟并论证配置决策 领域 4(16%)
AI 无法自行获知实时信息 → 必须靠工具 识别 LLM 系统的风险、局限与失效模式(知识截止) 领域 5(14%)
SSE 流式回传、findings 逐条持久化 可观测性;监控策略 领域 3
「形状不变,只换工具与管路」 架构复用与可扩展性论证 领域 1

🔤 本课新生词(已回灌 30-单词表/03,2026-10-14)

词汇 音标 释义 备注
⭐ agentic /əˈdʒentɪk/ 智能体式的、自主代理的 ⭐ 本课核心形容词
agentic workflow — 智能体工作流
⭐⭐ autonomous /ɔːˈtɑːnəməs/ 自主的 智能体定义要件 ①
⭐⭐ without a human in the middle — 中间没有人 ⭐ 定义要件 ③,高频考点
both sides of the loop — 循环的两侧 定义要件 ②
look at the result — 看结果 循环动作
keep going — 继续
easiest way to — 最简单的做法
⭐ implement /ˈɪmplɪment/ 实现
available — 可用的 with tools available
⭐ final answer — 最终答案 与 tool request 二分
execute(v.) /ˈeksɪkjuːt/ 执行
⭐⭐ stop reason — 停止原因 ⭐ response.stop_reason
⭐⭐ end_turn — 回合结束(终止信号) ⭐ 循环出口
⭐⭐ tool_use — 工具使用(block 类型 / stop reason) ⭐ 循环继续信号
alternate(v.) /ˈɔːltərneɪt/ 交替 the turns alternate
kick off — 起头、启动
⭐ minimal working example — 最小可运行示例 工程常用语
end to end — 端到端
drag in — 拖进来(牵扯进) without dragging in a database
⭐ wire up — 接线、接上 第 1 课已收,此处复现
fake / mock — 假的 / 模拟的 同义
on its own — 靠它自己 no way to know ... on its own
⭐ input_schema — 入参模式(JSON Schema) tools 三要素之一
properties — 属性(schema 字段)
required — 必填(schema 字段)
hardcoded lookup — 硬编码查询
⭐ hit(v.) — 打(数据库/接口) hit your database, an API
⭐ iteration /ˌɪtəˈreɪʃn/ 一次迭代
⭐ switch on — 依据……分支 switches on the stop reason
⭐ break(v.) — 跳出循环
tool result — 工具结果
⭐⭐ tool_use_id — 工具调用 ID(配对键) ⭐ 必考
⭐ push back into — 塞回、追加回 push ... back into messages
breathable /ˈbriːðəbl/ 透气的 输出内容词
⭐ compliance /kəmˈplaɪəns/ 合规 生产案例
structural report — 结构(安全)报告
building codes — 建筑规范
⭐ one by one — 一条条地 writes ... one by one as it works
mock lookup — 模拟查询
⭐ server-sent events (SSE) — 服务端推送事件 ⭐ 流式回传标准
stream back — 流回
⭐ persist(v.) /pərˈsɪst/ 持久化
risk-finding table — 风险发现表
⭐ plumbing — 管路、底层管线 第 1 课 Infrastructure 层已收,此处复现
identical /aɪˈdentɪkl/ 完全相同的 the shape ... is identical
observe, decide, act, repeat — 观察、决策、行动、重复 ⭐ 循环四步口诀
⭐ reasoning /ˈriːzənɪŋ/ 推理 the AI owns the reasoning

✅ 本课进度

  • [x] 全文精译与架构师级拆解(2026-10-14)
  • [x] ⭐⭐ 记录智能体定义三要件与 without a human in the middle
  • [x] ⭐⭐ 记录五步循环、stop_reason 二分与「2-1-1」最小计数
  • [x] ⭐⭐ 记录 tool_use_id 配对与「工具结果放 user role」两个实现陷阱
  • [x] ⭐⭐ 记录责任划分原句(You own the loop and the tools…)与 002 的接口
  • [x] 记录「形状不变,只换工具与管路」论断及其与前两课的串联
  • [x] 记录官方两处循环动词顺序不一致(act/observe/decide vs observe/decide/act)
  • [x] 英文原文已存:19-English-04-The-agent-loop-explained.md
  • [x] 生词回灌 30-单词表/03-考试核心生词与术语表.md(2026-10-14 建表,301 条入速查区,⭐⭐ 28 条精讲)
  • [ ] 官方未提供 What you'll learn 区块 —— 若后续页面补全,需回填

🔗 关联

⚠️ 语料说明:英文原文中的 anthropic.the AI provider() 与 model="current-model-fast" 为抓取/环境替换残留(按第 3 课映射对应 Sonnet 档),已在代码段下方说明;其余英文引句与代码均为官方原句,未作改动。

输入至少 2 个字符,检索全部课程与单词表