Skip to content
Agent Field Notes
Practice topicsFilter practice questions by topic.All practice →
knowledge unit 07FundamentalsConceptsAbout 12 minutes

Understand → Implement → Debug → Design

Control and completion criteria in agent loops

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

Agent LoopbudgetTermination conditionCancel

Knowledge content check2026-10-03 · Check the source of the original question2026-10-02

Which step do you want to learn from this knowledge point?

Select the starting point based on the current basis, or you can go deeper one by one. When you encounter an unfamiliar concept, go back to the core principles first; use the knowledge exercises to check your understanding when you are finished.

Understand first

New to this knowledge point

Complete the prerequisite concepts, read the principles and counterexamples, and then explain why in your own words.

Start with core principles →

Implement next

Prepare to write the principles into code

Understand implementation steps and boundaries, complete small tasks, and check results against acceptance requirements.

Reading implementation and trade-offs →

Debug failures

Need to handle failures and changes in conditions

Follow the continuous questioning to locate the failure premise, and then compare the migration cases to explain how the plan should be adjusted.

Continue to delve deeper into the problem →

Compare designs

Need to design or review plans

Combine engineering deductions and senior self-evaluation standards to explain the applicable conditions, costs and alternatives of the plan.

Analyze engineering scenarios →
Knowledge unit directory

LEARN · PRACTICE · REFLECT

Knowledge learning and personal records

My notes and review ↗

First read along the principles, Q&A and migration cases. When you need to check your understanding, switch to reinforcement exercises or start personal recording.

Answers and personal notes

Each modified commit will be kept as an independent history. Your level of mastery is up to you to evaluate yourself against the standards.

Core concept · Control and completion criteria in agent loops

Understand the core principles first

Preparatory concepts:Request life cycle, Asynchronous cancellation, Business acceptance

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.

Visual guide · Stopping the loop differs from proving success

Stopping the loop differs from proving success

The model proposes the next step; runtime enforces execution limits. Terminal labels preserve effects and uncertainty. Select the figure to open it at full size.

View the loop from an HTTP request

A conventional backend follows a defined program after receiving a request. An agent adds model-proposed next actions. The decision source changes, but server responsibilities for permissions, cost, and effects remain. The loop generates candidate actions, checks them at the gateway, executes them, and updates recorded facts. Final prose is a candidate artifact.

A round limit is insufficient

One round can make several calls, each with retries. Limiting rounds alone resembles limiting transactions without limiting their SQL operations. Bound model rounds, actual call attempts, concurrency, and absolute deadlines separately; account for actual usage. OpenAI Runner’s maximum turns protects the loop, while the application must enforce business budgets.

Terminal states require evidence

“Fixed” does not establish a passing test; “cancelled” does not erase a submitted release. Separate task state from operation states so a stopped task can retain completed effects and unresolved outcomes. A test model that declares completion early or repeatedly requests tools can expose control failures more reliably than one successful live-model run.

Check understanding with a question

How does the Agent loop stop? How to draw the boundary between model decision-making and runtime control?

Compare with the reference answer

The model proposes actions; runtime executes permitted tools, returns results to context, and continues the loop. Runtime independently enforces permissions, rounds, time, and cost. Business evidence determines success. Budget exhaustion and tool failure are distinct terminal outcomes. Record the stopping reason and verified artifacts so users can see completed and outstanding work.

Implementation and trade-offs

Runtime controls the loop

A response can contain an answer or several proposed tool calls. Runtime dispatches authorized calls, collects results, and decides whether to continue. OpenAI Agents Runner returns tool results to the model and bounds turns with max_turns. Count individual executions and internal retries independently. Supply goals, allowed actions, and evidence to the model while keeping identities, credentials, and authoritative budgets on the server.

Define terminal states and budgets

Distinguish succeeded, failed, canceled, waiting_approval, and budget_exhausted. Success needs artifacts and passing checks; a completion claim is only a candidate. Bound model rounds, tool attempts, duration, and cost. Reserve estimated costs before calls and settle actual usage afterward through a shared ledger. Exhaustion preserves completed artifacts and outstanding work without unlimited retries.

Cancellation must propagate

Block new actions, then cancel supported running calls. Reconcile already-dispatched writes; a local timeout cannot establish non-execution. Separate transient failures, authorization denial, and permanent business errors. Retry only suitable idempotent operations. Repeated identical failures trigger diagnosis or termination. Record run_id, turn, tool_call_id, duration, and stop reason with payload redaction.

Test control boundaries

Use fixed model responses that repeat tools, propose parallel calls, declare success prematurely, or encounter cancellation. Assert limits stop dispatch, failures do not become succeeded, cancellation prevents new effects, and failed artifact checks lead to repair or explicit failure. Validate these controls before live-model completion measurements. Concrete counterexamples demonstrate implementation more clearly than a loop slogan.

Engineering deduction

scene
Hypothetical engineering scenario: After the R&D Agent repairs the interface, it repeatedly runs the same failed test, and the task never ends.
design decisions
Set up shared budgets and repeated action detection, and convert failure logs into structured diagnostics; success must be accepted through the specified interface.
Verify target
Expected behavior: Repeated failures trigger a restricted end, retaining modification and error evidence; only runs that pass acceptance will enter the successful final state.
applicable boundary
This is a design example and does not claim real team performance improvement metrics; budget thresholds need to be calibrated based on specific task distribution.

Continuous questions and answers

Continue reading along with the premises and constraints of the problem. Understand the reference answers first, then try to put away the answers and explain the cause and effect and trade-offs in your own words.

Draw inferences from one example: If the conditions change, how to deduce it?

First find out the conditions for change, and then determine which premises in the original plan still hold true. The following cases are teaching deductions to facilitate the transfer of principles to new problems.

Research assignment has no definite answer

Changing conditions:Acceptance changes from automatic testing to evidence coverage and manual judgment

Extended question:How to judge the completion of data research?

Derivation and reference solutions

Start by defining the scope of coverage, the types of sources that must be consulted, how references can be read back, and how open questions are presented. References and required fields can be automatically checked during runtime, and disputed conclusions are submitted to manual or specialized review. Reaching the scope and truthfully reporting unknowns counts as completion. The model cannot be required to guarantee that nothing is missing in the world, nor can the number of searches be used as a substitute for evidence coverage.

The principles that remain unchanged:Completion always relies on predefined observable conditions, it's just that the validator changes from testing to evidence review.

Scheduled tasks run repeatedly

Changing conditions:One task becomes multiple runs per day

Extended question:After today's failure, can yesterday's success status be automatically used tomorrow?

Derivation and reference solutions

Each run binds a snapshot of the input with proof of acceptance. The facts published yesterday can be reused, today's data refresh, permissions and budgets are rechecked; the same business actions continue to use the same operation keys, and new date artifacts use new business identifiers. One success cannot overwrite a failure under new input, and the system should display the results of each run separately.

The principles that remain unchanged:Task lifecycle and business operation lifecycle must be separated.

Easy to make mistakes

  • Treat max_turns as the total cost or total number of tools limit
  • Directly map the final text of the model to business success
  • Tools that retry unconditionally after timeout have side effects

References

It is designed based on public technical information; the reference materials support the technical mechanism, and the scenarios and scoring standards are designed by this website and do not represent the original interview questions of a certain company. New Q&A and migration cases are added for principle explanation, and source verification and case operation verification are recorded separately.

Check how far you understand

After reading, you can explain the principles, boundaries, and trade-offs against these standards. It is up to you to evaluate your mastery; if further verification is needed, complete the small tasks below.

Basic standards met
It can distinguish between model proposal completion and business acceptance, and provide bounded stopping conditions.
Intermediate and advanced signals
Implement rounds, tool counts, fees, cancellations, and error classifications into runtime.
Senior criteria
Can explain the unknown state of shared budget reservation and external actions, and verify it with counterexamples.

Hands-on verificationComplete on demand · Suggestions15 minutes

Draw a state machine for a tool loop and simulate the model requiring the same failure action three times in a row.

Expand acceptance requirements and checkpoints
  • Repeated failures will result in bounded termination.
  • A model’s completion claim must still pass acceptance checks.
  • The reason for stopping is traceable.

Key inspections

  • Can explain the difference between model call rounds and tool execution times
  • Distinguish final text from business acceptance
  • Provide budget, cancellation, exception final status and recording method