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.