73 / 90

Day 73:使用工具的 Agent 控制循环——模型请求、动作与观察

讲清 请求→动作→观察 循环,预测有界 Agent 的运行轨迹,并在真实的确定性 Learning Project 上验证其可观察行为。

Agent(智能体) 480 分钟有效研习(8 小时)
01 120 分钟

模型请求与“动作—观察”控制循环

Agent 辅助工程检查

前置要求

Day 70-72 的模型评估概念,以及随 Agent 工具路线引入的有界 Agent Learning Project(projects/agent_learning)。

学习目标

解释使用工具的 Agent 控制循环的五个阶段——模型请求、动作提案、工具分发、结构化观察、继续循环或终止——并把每个阶段映射到确定性的 projects.agent_learning 实验装置上。

操作指引

学习来源:在本活动现有的阅读与练习时段内,参考 Hugging Face Agents Course: Introduction to Agents 的 Unit 1: What is an Agent?; What are Tools?; agent workflow; Summary; Quiz,用自己的话解释一处与本地任务的联系。保留现有练习与验收检查;若外部资料无法访问,使用课程自写的解释。1. 控制循环:每一步运行时把任务、对话历史与可用工具 Schema 发给模型;模型返回一个动作提案;运行时验证后把它分发到有界工具;工具的结构化观察被追加到历史中;循环重复直至某个终止条件触发。
2. ReAct(Yao 等,2022)在真实环境中把推理轨迹与动作交错。本 Learning Project 刻意只保留 action 与 observation 事件——从不记录 thought 或 chain_of_thought 字段,因此你收集的证据是可观察行为,而不是隐藏推理。
3. 装置的状态图:
IDLE -> MODEL_REQUEST -> ACTION_PROPOSED -> TOOL_DISPATCH -> OBSERVATION ->(回到 MODEL_REQUEST)... -> TERMINATE
run_task 的终止原因:goal_reached(write_report 观察为 ok)、tool_failure(失败观察数超过 max_retries)、step_budget(步数先达到 max_steps)。
4. 在有界项目中:DeterministicModelAdapter.next_action(history) 扮演模型角色;_tool_call(action, workspace) 负责验证与执行;run_task 掌管循环与预算;evaluate() 事后独立地重新评分工作区产物。
5. 诚实边界:该装置演示循环结构与错误词汇,并未实现 JSON-RPC 帧、能力协商或流式传输——它是教学模型,不是协议合规客户端。

自主演练与记录

在运行任何东西之前,写出你对 fixture summarize-notes 预测的有序动作列表(工具名加参数)、预测的最终 status、steps、retries 与终止原因。

独立掌握标准

能独立说出全部五个循环阶段、三个终止原因及触发条件,并说明为什么动作/观察证据不包含隐藏的思维链。

权威源资源与权利证明

linking Apache-2.0

Hugging Face Agents Course: Introduction to Agents

作者 / 机构: Hugging Face agents-course contributors | 原始出处链接 ↗

对应章节 / 时间戳: Unit 1: What is an Agent?; What are Tools?; agent workflow; Summary; Quiz

验证版本与日期: Public edition checked 2026-11-01; moving pages may change

入选理由:

A sequenced introduction, examples and quizzes before formal ReAct/tool API references. Adopt the control-loop concepts, not framework-specific execution or private-reasoning logs.

来源前置条件:

Python, language-model messages and JSON; local agent exercises use only action/observation traces.

安全回退方案(离线弹性):

Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.

对比候选资源与选型分析 (2)
ReAct ↗ compared_alternative [Open Access / CC BY 4.0]

Retained as the method-definition paper; not a self-contained beginner exercise course.

Anthropic tool use docs ↗ compared_alternative [Anthropic PBC copyright (no open license)]

Retained for one protocol example; vendor message formats are not interchangeable.

linking Open Access / CC BY 4.0

ReAct: Synergizing Reasoning and Acting in Language Models

作者 / 机构: Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, Yuan Cao | 原始出处链接 ↗

对应章节 / 时间戳: Section 3 & 4 (ReAct Formulation and Synergy)

验证版本与日期: ICLR 2023 / arXiv:2210.03629v2 (Verified: 2026-10-30)

入选理由:

Foundational academic paper introducing the interleaved Thought-Action-Observation control loop in LLM agents, establishing formal interleaving of task reasoning and external tool execution.

来源前置条件:

Prompt engineering, token generation basics, and conversational interaction loops.

安全回退方案(离线弹性):

Complete algorithmic step traces, state loop diagrams, and control loop pseudocode are self-contained in curriculum materials.

对比候选资源与选型分析 (2)

Pure reasoning without environmental actions or external tool grounding; ReAct extends reasoning into an interactive environment action-observation loop.

Early neuro-symbolic modular router concept; ReAct offers simpler, prompting-native action-observation loop dynamics suitable for standard API models.

linking arXiv.org perpetual non-exclusive license / Open Access

Toolformer: Language Models Can Teach Themselves to Use Tools

作者 / 机构: Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta Raileanu, Maria Lomeli, Luke Zettlemoyer, Nicola Cancedda, Thomas Scialom | 原始出处链接 ↗

对应章节 / 时间戳: Section 2 (Approach: Tool Use and Filtering)

验证版本与日期: NeurIPS 2023 / arXiv:2302.04761v1 (Verified: 2026-10-30)

入选理由:

Original paper demonstrating self-supervised discovery and execution of tool API calls (calculator, QA, search, calendar) via inline tokenized tool invocations.

来源前置条件:

Transformer autoregressive generation, API calling syntax, and self-supervised filtering.

安全回退方案(离线弹性):

Inline tool invocation formats and self-contained mock execution traces are provided in curriculum notes.

对比候选资源与选型分析 (2)
Gorilla: Large Language Model Connected with Massive APIs (Patil et al. 2023) ↗ compared_alternative [Apache-2.0 / arXiv Open Access]

Focuses on massive API retrieval and documentation formatting; Toolformer focuses on the fundamental token-level seam between model generation and tool execution.

TALM: Tool Augmented Language Models (Parisi et al. 2022) ↗ compared_alternative [arXiv Open Access]

Iterative search-and-execute augmentation; Toolformer provides clearer self-supervised API call tokenization syntax.

02 120 分钟

summarize-notes 装置的轨迹预测

独立掌握检查(无 AI 辅助)

前置要求

Day 73 活动 1:五阶段控制循环与三种终止原因。

学习目标

在执行装置之前,产出一份书面的、可证伪的完整事件轨迹预测——每个动作名、参数对象与观察 ok 标志。

操作指引

1. 阅读 projects/agent_learning/README.md 与 fixtures.py:create_fixture 写入 notes/alpha.txt 与 notes/beta.txt;expected_report() 是两者内容的拼接。
2. 从 next_action 的策略推导出精确的工具顺序与参数。
3. 编写 prediction.json,包含 4 个事件,每个形如 {"action": {"name": ..., "arguments": {...}}, "observation": {"ok": true, ...}},并附预测的 RunResult 字段。
4. 同时预测观察负载的键:list_notes 返回 files(排序后的名字);read_note 返回 filename 与 content;write_report 返回 path。
5. 把不确定之处(例如文件是否排序)明确记为待对照真实运行检验的开放问题。

自主演练与记录

编写含 4 个轨迹事件和预测 RunResult 字段(status、steps、retries、termination)的 prediction.json。活动 3 的真实运行之后给自己打分。

独立掌握标准

在看到真实运行之前,独立产出动作名与参数都与实测一致的预测;漏项要诚实记入日志。

权威源资源与权利证明

linking Open Access / CC BY 4.0

ReAct: Synergizing Reasoning and Acting in Language Models

作者 / 机构: Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, Yuan Cao | 原始出处链接 ↗

对应章节 / 时间戳: Section 3 & 4 (ReAct Formulation and Synergy)

验证版本与日期: ICLR 2023 / arXiv:2210.03629v2 (Verified: 2026-10-30)

入选理由:

Foundational academic paper introducing the interleaved Thought-Action-Observation control loop in LLM agents, establishing formal interleaving of task reasoning and external tool execution.

来源前置条件:

Prompt engineering, token generation basics, and conversational interaction loops.

安全回退方案(离线弹性):

Complete algorithmic step traces, state loop diagrams, and control loop pseudocode are self-contained in curriculum materials.

对比候选资源与选型分析 (2)

Pure reasoning without environmental actions or external tool grounding; ReAct extends reasoning into an interactive environment action-observation loop.

Early neuro-symbolic modular router concept; ReAct offers simpler, prompting-native action-observation loop dynamics suitable for standard API models.

linking IETF Trust License / Open Standard

RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

作者 / 机构: Tim Bray (Ed.) | 原始出处链接 ↗

对应章节 / 时间戳: Section 1-4 (JSON Syntax and Grammar)

验证版本与日期: IETF Standards Track RFC 8259 (Verified: 2026-10-30)

入选理由:

Foundational Internet standard defining strict JSON grammar, token parsing, and whitespace rules underpinning model tool calling serialization.

来源前置条件:

Text encoding, UTF-8 parsing, and serialized data exchange.

安全回退方案(离线弹性):

JSON grammar parsing rules and error recovery guidelines are documented in curriculum notes.

对比候选资源与选型分析 (2)
RFC 7049: Concise Binary Object Representation (CBOR) ↗ compared_alternative [IETF Open Standard]

Binary serialization standard; text-based LLMs operate primarily on human-readable UTF-8 JSON interchange formats.

YAML 1.2 Specification (OASIS / yaml.org) ↗ compared_alternative [Open Standard]

Indentation-sensitive text format; JSON has universally standardized parsing across language runtimes and tool schemas.

03 120 分钟

执行有界 Agent 并检查动作/观察事件

Agent 辅助工程检查

前置要求

Day 73 活动 2:本次执行前已存在书面轨迹预测。

学习目标

运行公开 CLI、捕获 JSON 产物、对预测与实测轨迹做差异比对,并确认产物只记录 action/observation 事件。

操作指引

1. 在仓库根目录执行:
python -m projects.agent_learning.cli evaluate --fixture summarize-notes --output /tmp/agent-run.json
2. 检查 result.trace:每个事件必须恰好只有 action 与 observation 两个键;observation.ok 标志驱动重试计数。
3. 检查 evidence 块:model_adapter 为 "deterministic-v1"(装置替身而非真实模型)、network 为 "disabled"、trace_policy 为 "actions and observations only"。
4. 把你的 prediction.json 与该产物做 diff:记录每一处不一致及其根因。
5. 再次运行同一命令,确认两份产物逐字节一致——确定性行为才让证据可以被核查。

自主演练与记录

执行 CLI 两次并保存两份产物,验证:(a) 两者完全一致;(b) 任何位置都不出现 thought 或 chain_of_thought 键;(c) report.metrics 显示四个评分维度全部通过。

独立掌握标准

验证了逐字节一致的重跑、思维链键零命中的扫描结果以及成文的预测差异分析;可以让 Agent 帮忙跑命令,但差异分析必须自己做。

权威源资源与权利证明

linking Anthropic PBC copyright (no open license stated) / linked reference Linking only; no documentation text is copied

Anthropic Tool Use (Function Calling) Implementation Guide

作者 / 机构: Anthropic PBC | 原始出处链接 ↗

对应章节 / 时间戳: Tool Use Overview, Schema Definitions, and Stop Reasons

验证版本与日期: Claude API Specification (Verified: 2026-10-30)

入选理由:

Detailed production reference for client-side tool definitions, tool_use content blocks, stop reason tool_use, and tool_result response formatting.

来源前置条件:

REST API concepts, JSON schema specification, and basic Python client programming.

安全回退方案(离线弹性):

Offline mock request/response cycles and tool payload schemas are provided in the repo.

对比候选资源与选型分析 (2)
Google Gemini Function Calling Documentation ↗ compared_alternative [Creative Commons Attribution 4.0]

Protobuf and REST function declaration schema; Anthropic documentation provides explicit structured message block mechanics (tool_use / tool_result).

Cohere Tool Use and Multi-Step Agents Guide ↗ compared_alternative [Open Documentation]

Multi-step tool calling parameter definitions; Anthropic specification demonstrates clear separated content blocks essential for inspectable event traces.

linking OpenAI copyright (no open license stated) / linked reference Linking only; no documentation text is copied

OpenAI Function Calling and Structured Outputs Guide

作者 / 机构: OpenAI | 原始出处链接 ↗

对应章节 / 时间戳: Function Calling Architecture and Strict Outputs

验证版本与日期: OpenAI API Reference (Verified: 2026-10-30)

入选理由:

Widely adopted specification establishing tool choice parameters, JSON schema function descriptions, tool_calls arrays, and role: "tool" responses.

来源前置条件:

JSON data structures, chat completion roles, and schema validation.

安全回退方案(离线弹性):

Standard schema dictionaries and simulated tool call responses are bundled in the repository.

对比候选资源与选型分析 (2)
Mistral AI Function Calling Guide ↗ compared_alternative [Open Documentation]

Follows OpenAI-compatible schema convention; OpenAI documentation serves as the primary originating reference for tools and tool_calls schemas.

Ollama Tools and Function Calling Documentation ↗ compared_alternative [MIT / Open Documentation]

Local model runtime implementation of function calling; OpenAI docs document the standard schema contract and strict output validation.

04 120 分钟

评估:控制循环状态机与终止条件审计

独立掌握检查(无 AI 辅助)

前置要求

完成 Day 73 活动 1-3 并保存了轨迹产物。

学习目标

独立重建控制循环状态机,枚举每个终止原因及其精确触发条件,达到独立掌握检查的评分标准。

操作指引

1. 凭记忆画出状态图:IDLE -> MODEL_REQUEST -> ACTION_PROPOSED -> TOOL_DISPATCH -> OBSERVATION -> 回到循环或 TERMINATE。
2. 填写终止表:goal_reached = write_report 观察 ok;tool_failure = 累计失败观察超过 max_retries(默认 2);step_budget = 步数先达到 max_steps(默认 6)。
3. 独立评分标准:三个原因及触发条件全部正确、五个阶段至少说出四个、无协助。
4. 协助评分标准(Agent 协同工程检查):可以让 Agent 帮你定位 run_task 的行,但计数器必须由你亲自对照源码与保存的产物核实。
5. 用两句话解释为什么 evaluate() 要重新读取工作区产物而不是采信适配器的自我报告。

自主演练与记录

不打开 agent.py 完成终止表与状态迁移列表;随后对照源码核对并把修正记入日志。

独立掌握标准

独立掌握检查:三个终止原因及触发条件全部正确、五个循环阶段至少说出四个,且无协助。

权威源资源与权利证明

linking Open Access / CC BY 4.0

ReAct: Synergizing Reasoning and Acting in Language Models

作者 / 机构: Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, Yuan Cao | 原始出处链接 ↗

对应章节 / 时间戳: Section 3 & 4 (ReAct Formulation and Synergy)

验证版本与日期: ICLR 2023 / arXiv:2210.03629v2 (Verified: 2026-10-30)

入选理由:

Foundational academic paper introducing the interleaved Thought-Action-Observation control loop in LLM agents, establishing formal interleaving of task reasoning and external tool execution.

来源前置条件:

Prompt engineering, token generation basics, and conversational interaction loops.

安全回退方案(离线弹性):

Complete algorithmic step traces, state loop diagrams, and control loop pseudocode are self-contained in curriculum materials.

对比候选资源与选型分析 (2)

Pure reasoning without environmental actions or external tool grounding; ReAct extends reasoning into an interactive environment action-observation loop.

Early neuro-symbolic modular router concept; ReAct offers simpler, prompting-native action-observation loop dynamics suitable for standard API models.

linking Open Access / CC BY 4.0

Reflexion: Language Agents with Verbal Reinforcement Learning

作者 / 机构: Noah Shinn, Federico Cassano, Ashwin Gopinath, Karthik Narasimhan, Shunyu Yao | 原始出处链接 ↗

对应章节 / 时间戳: Section 2 & 3 (Reflexion Architecture and Memory Buffer)

验证版本与日期: NeurIPS 2023 / arXiv:2303.11366v4 (Verified: 2026-10-30)

入选理由:

Rigorous framework analyzing dynamic error feedback, memory buffering of execution failures, and controlled self-reflection loops without updating model weights.

来源前置条件:

Reinforcement learning concepts, agent evaluation loops, and error feedback handling.

安全回退方案(离线弹性):

Error recovery state diagrams and retry budget algorithms are detailed in curriculum materials.

对比候选资源与选型分析 (2)

Single-turn generative text refinement; Reflexion operates across multi-turn external environment action-observation failures.

Domain-specific LLM-based agent for open-world Minecraft; Reflexion establishes domain-general verbal feedback control loops.