73 / 90

Day 73: The Tool-Using Agent Control Loop - Model Requests, Actions, and Observations

Explain the request-to-action-to-observation cycle, predict the bounded agent's trace, and verify its observable behavior on the real deterministic Learning Project.

Agents 480 active minutes (8 hours)
01 120 min

Model Requests and the Action-Observation Control Loop

Agent-Assisted Engineering Check

Prerequisites

Days 70-72 model evaluation concepts and the bounded agent Learning Project (projects/agent_learning) introduced with your Agent Tool Track.

Learning Objective

Explain the five stages of a tool-using agent's control loop - model request, action proposal, tool dispatch, structured observation, and loop-or-terminate - and map each stage onto the deterministic projects.agent_learning harness.

Instructions

Study source: within this activity's existing reading/practice time, use Hugging Face Agents Course: Introduction to Agents, Unit 1: What is an Agent?; What are Tools?; agent workflow; Summary; Quiz, then explain one connection to the local task in your own words. Keep the local exercise and acceptance checks; use its original explanation if the external source is unavailable. 1. The control loop: on every step the runtime sends the task plus conversation history plus available tool schemas to the model; the model returns one proposed action; the runtime validates and dispatches it to a bounded tool; the tool's structured observation is appended to history; the loop repeats until a termination condition fires.
2. ReAct (Yao et al. 2022) interleaves reasoning traces with actions in a real environment. Our Learning Project deliberately keeps only action and observation events - it never records thought or chain_of_thought fields, so the evidence you collect is observable behavior, not hidden reasoning.
3. State diagram for the harness:
IDLE -> MODEL_REQUEST -> ACTION_PROPOSED -> TOOL_DISPATCH -> OBSERVATION -> (back to MODEL_REQUEST) ... -> TERMINATE
Termination reasons in run_task: goal_reached (a write_report observation is ok), tool_failure (failed observations exceed max_retries), step_budget (the step counter reaches max_steps first).
4. In the bounded project: DeterministicModelAdapter.next_action(history) plays the model role; _tool_call(action, workspace) validates and executes; run_task owns the loop and budgets; evaluate() independently re-scores the workspace artifacts afterward.
5. Honest scope: the fixture demonstrates loop shape and error vocabulary. It does not implement JSON-RPC framing, capability negotiation, or streaming - it is a teaching model, not a protocol-compliant client.

Practice & Prediction Log

Before running anything, write your predicted ordered action list for fixture summarize-notes (tool names plus arguments), the predicted final status, steps, retries, and termination reason.

Independent Mastery Criterion

Independently name all five loop stages, all three termination reasons with triggers, and state why action/observation evidence excludes hidden chain-of-thought.

Authoritative Source Resources & Provenance

linking Apache-2.0

Hugging Face Agents Course: Introduction to Agents

Author: Hugging Face agents-course contributors | Original Source Link ↗

Relevant Section / Range: Unit 1: What is an Agent?; What are Tools?; agent workflow; Summary; Quiz

Verified Version & Date: Public edition checked 2026-11-01; moving pages may change

Selection Rationale:

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.

Source Prerequisites:

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

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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

Author: Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, Yuan Cao | Original Source Link ↗

Relevant Section / Range: Section 3 & 4 (ReAct Formulation and Synergy)

Verified Version & Date: ICLR 2023 / arXiv:2210.03629v2 (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

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

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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

Author: Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta Raileanu, Maria Lomeli, Luke Zettlemoyer, Nicola Cancedda, Thomas Scialom | Original Source Link ↗

Relevant Section / Range: Section 2 (Approach: Tool Use and Filtering)

Verified Version & Date: NeurIPS 2023 / arXiv:2302.04761v1 (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

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

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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 min

Trace Prediction for the summarize-notes Fixture

Independent Mastery Check (no AI assistance).

Prerequisites

Day 73 Activity 1: the five-stage control loop and the three termination reasons.

Learning Objective

Produce a written, falsifiable prediction of the complete event trace - every action name, arguments object, and observation ok flag - before executing the harness.

Instructions

1. Read projects/agent_learning/README.md and fixtures.py: create_fixture writes notes/alpha.txt and notes/beta.txt; expected_report() is the concatenation of both contents.
2. From next_action's policy, derive the exact ordered tool sequence and arguments.
3. Write prediction.json containing four events, each shaped {"action": {"name": ..., "arguments": {...}}, "observation": {"ok": true, ...}} plus your predicted RunResult fields.
4. Predict the observation payload keys too: list_notes returns files (sorted names); read_note returns filename and content; write_report returns path.
5. Mark anything you are unsure about (for example whether files are sorted) as an explicit open question to check against the real run.

Practice & Prediction Log

Write prediction.json with 4 trace events and the predicted RunResult fields (status, steps, retries, termination). Score yourself after the real run in Activity 3.

Independent Mastery Criterion

Produce an independent prediction whose action names and arguments match the real run before seeing it; note any misses honestly in your log.

Authoritative Source Resources & Provenance

linking Open Access / CC BY 4.0

ReAct: Synergizing Reasoning and Acting in Language Models

Author: Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, Yuan Cao | Original Source Link ↗

Relevant Section / Range: Section 3 & 4 (ReAct Formulation and Synergy)

Verified Version & Date: ICLR 2023 / arXiv:2210.03629v2 (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

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

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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

Author: Tim Bray (Ed.) | Original Source Link ↗

Relevant Section / Range: Section 1-4 (JSON Syntax and Grammar)

Verified Version & Date: IETF Standards Track RFC 8259 (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

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

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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 min

Execute the Bounded Agent and Inspect Action/Observation Events

Agent-Assisted Engineering Check

Prerequisites

Day 73 Activity 2: a written trace prediction exists before this execution.

Learning Objective

Run the public CLI, capture the JSON artifact, diff predicted versus observed trace, and confirm the artifact records only action/observation events.

Instructions

1. From the repository root run:
python -m projects.agent_learning.cli evaluate --fixture summarize-notes --output /tmp/agent-run.json
2. Inspect result.trace: every event must have exactly the keys action and observation; observation.ok flags drive retry counting.
3. Inspect the evidence block: model_adapter is "deterministic-v1" (a fixture, not a live model), network is "disabled", trace_policy is "actions and observations only".
4. Diff your prediction.json against the artifact: record every mismatch and its root cause.
5. Re-run the command and confirm the two artifacts are byte-identical - deterministic behavior is what makes the evidence checkable.

Practice & Prediction Log

Execute the CLI twice, save both artifacts, and verify (a) they are identical, (b) no thought or chain_of_thought key appears anywhere, (c) report.metrics shows all four scoring dimensions passed.

Independent Mastery Criterion

Verify a byte-identical rerun, a zero-count chain-of-thought scan, and a documented prediction diff; an agent may help run commands but the diff analysis is yours.

Authoritative Source Resources & Provenance

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

Anthropic Tool Use (Function Calling) Implementation Guide

Author: Anthropic PBC | Original Source Link ↗

Relevant Section / Range: Tool Use Overview, Schema Definitions, and Stop Reasons

Verified Version & Date: Claude API Specification (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

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

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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

Author: OpenAI | Original Source Link ↗

Relevant Section / Range: Function Calling Architecture and Strict Outputs

Verified Version & Date: OpenAI API Reference (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

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

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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 min

Assessment: Control-Loop State Machine and Termination Audit

Independent Mastery Check (no AI assistance).

Prerequisites

Day 73 Activities 1-3 completed with a saved trace artifact.

Learning Objective

Independently reconstruct the control-loop state machine, enumerate every termination reason with its exact trigger, and meet the Independent Mastery Check rubric.

Instructions

1. From memory, draw the state diagram: IDLE -> MODEL_REQUEST -> ACTION_PROPOSED -> TOOL_DISPATCH -> OBSERVATION -> loop back or TERMINATE.
2. Fill the termination table: goal_reached = write_report observation ok; tool_failure = cumulative failed observations exceed max_retries (default 2); step_budget = steps reach max_steps (default 6) first.
3. Independent rubric: all three reasons plus triggers correct, at least four of five loop stages named, no assistance.
4. Assisted rubric (Agent-Assisted Engineering Check): you may ask an agent to locate run_task lines, but you must personally verify the counters against the source and the saved artifact.
5. Explain in two sentences why evaluate() re-reads workspace artifacts instead of trusting the adapter's self-report.

Practice & Prediction Log

Complete the termination table and the state transition list without opening agent.py; then verify your answer against the source and log any correction.

Independent Mastery Criterion

Independent Mastery Check: all three termination reasons with correct triggers and at least four of five loop stages, unaided.

Authoritative Source Resources & Provenance

linking Open Access / CC BY 4.0

ReAct: Synergizing Reasoning and Acting in Language Models

Author: Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, Yuan Cao | Original Source Link ↗

Relevant Section / Range: Section 3 & 4 (ReAct Formulation and Synergy)

Verified Version & Date: ICLR 2023 / arXiv:2210.03629v2 (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

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

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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

Author: Noah Shinn, Federico Cassano, Ashwin Gopinath, Karthik Narasimhan, Shunyu Yao | Original Source Link ↗

Relevant Section / Range: Section 2 & 3 (Reflexion Architecture and Memory Buffer)

Verified Version & Date: NeurIPS 2023 / arXiv:2303.11366v4 (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

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

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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.