Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Control and completion criteria in agent loops

Starting from the tool invocation loop, design termination conditions, budgets, cancellations, and verifiable completion statuses.

Learning objectives: Model output proposes the next step; the runtime owns execution and terminal state. Stopping only establishes that the loop ended. Success additionally requires evidence that the agreed business conditions hold. Budget exhaustion, cancellation, and unknown outcomes therefore need distinct labels rather than one generic 'completed' state.

Content checked: 2026-10-03 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Implementation · Build it. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Backend developers learning Agent applications.

Control and completion criteria in agent loops
Model output proposes the next step; the runtime owns execution and terminal state. Stopping only establishes that the loop ended. Success additionally requires evidence that the agreed business conditions hold. Budget exhaustion, cancellation, and unknown outcomes therefore need distinct labels rather than one generic 'completed' state.

How does the mechanism work?

Step-by-step explanation
  1. One model round generates five tool calls, how to budget?

    One round can contain multiple actions, so account for the abstract loop in the resource ledger.

  2. When the user cancels, the remote write operation has been successful. How do you end it?

    Cancellation signals affect execution; business effects that already occurred require separate follow-through.

  3. Is a correct answer successful if the model did not run the required tests?

    The terminal state must be determined by acceptance conditions, rather than how credible the text sounds.

Implementation · Build it

Implement and observe · Read the same task across route checkpoints

Objectives of this level: Read actual checkpoint and event fields without changing the ledger; explain why one task spans several invocations and why counters persist.

Visual guide · Model stop and business finish

Model stop and business finish

Only a bound merchant receipt completes the application. Approval, a final model answer and a timeout each establish different facts. Select the figure to open it at full size.

Start from the route artifacts

Use the extracted enterprise-after-sales-agent-v1 directory after completing its response, prompt and tool route stages. It must contain agent.py, store.py, model_adapter.py, and work/response.json, work/prompt.json, work/tool.json. These are locally generated records, not prewritten model-quality claims. If a file is missing, finish the corresponding README route stage first. Run this read-only script from that extracted directory; it does not call the model, merchant or database.

import json
from pathlib import Path

for name in ["response", "prompt", "tool"]:
    record = json.loads((Path("work") / (name + ".json")).read_text())
    task = record.get("task", record)
    events = task["events"]
    responses = [e for e in events if e["kind"] == "model_response"]
    tools = [e for e in events if e["kind"] == "tool"]
    calls = [(e["payload"]["name"], e["payload"]["call_id"]) for e in tools]
    assert task["turn_count"] == len(responses)
    assert task["tool_count"] == len(tools)
    print(json.dumps({"stage": name, "task": task["id"], "status": task["status"],
        "turns": task["turn_count"], "tools": task["tool_count"], "calls": calls,
        "has_business_receipt": task["receipt"] is not None}, sort_keys=True))

Expected output and its cause

The three rows have the same task ID main-return:

  1. response: queued, turns 1, tools 1, call get_order/call-1, no receipt.
  2. prompt: queued, turns 2, tools 2, adding retrieve_policy/call-2, no receipt.
  3. tool: awaiting_approval, turns 4, tools 3, adding propose_return/call-3, no receipt.

rounds=1 bounds one invocation, then Agent.run records queued. It does not reset the lifetime counters. The final model round has text rather than a tool call, so turns rise from three to four while tools remain three. finish_answer checks the citations/proposal and records awaiting_approval. A later invocation reloads the transcript; an already committed tool_receipts entry keyed by (task_id, call_id) can recover its result. The tool receipt is still distinct from the merchant business receipt.

Open Agent.run and locate batch preflight, pending-call recovery and budget checks. Open Agent.tool and locate the receipt commit/counter increment. Mark where a process failure before or after these commits changes what can be safely resumed. The script verifies this successful deterministic route; it does not prove all failures are bounded or that a real model will choose the same actions.

Independent reader work

Implement your own checkpoint_summary(record) in a separate scratch file before copying this reference. Return task ID, state, committed model turns, committed tool results and whether a business receipt exists. It must accept both the direct task shape (response.json) and wrapper shape (tool.json). Compare your three outputs with the expected rows and explain the one-turn difference at the last checkpoint.

code example

A saved tool result at a crash boundary

If a tool result and receipt were committed but its function_call_output was not yet appended, resumption can find the saved call_id and reconstruct the result without re-running that tool. A different argument hash under that same ID is a conflict. This recovery mechanism does not prove an external business write was absent.

Acceptance task for this level

Write checkpoint_summary in your own scratch file, run it against the three completed route records, and annotate the matching commit points in Agent.run / Agent.tool. Submit the output and the final text-round explanation.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Why does the tool checkpoint contain four model responses but only three committed tools?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (1 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.