Loop Control and Governance

By the Syncfusion DevTutorials team · Last updated

How to decide when an agent loop stops and how much it may use: stop conditions, step, token, time and cost budgets, soft and hard limits, progress checks, and a clean final report.

Think about a taxi ride with a meter.

You tell the driver where you want to go. The ride ends when you arrive at your destination.

It can also end if you ask the driver to stop early. The meter keeps running during the trip, so you can see the cost and avoid unexpected charges.

A good agent loop works in a similar way. It knows when the goal has been reached.

It can stop when instructed to stop. It also tracks how many resources it is using so it cannot spend more than allowed.

The main idea: Loop control decides when the agent should stop and how many resources it can use. Governance monitors the loop while it runs and ensures it finishes cleanly.

A Real-World Example

Imagine running a coding agent on a large project overnight. The next morning, one of three things may have happened:

  1. It fixed the bug in 6 steps and stopped. Good.
  2. It got stuck, repeated the same action 400 times, and used your entire monthly AI budget. Bad.
  3. It noticed it was stuck after repeating the same action 3 times, stopped, and left a clear report. Good.

The difference between story 2 and story 3 is loop control.

In simple words: Tell the agent when to stop and set a resource budget. Monitor it while it runs and make sure it produces a clear report at the end.

What You Will Learn

In this lesson, you will learn:

  1. Three stop conditions: goal completion, exit signals, and interrupts.
  2. Four types of budgets: steps, tokens, time, and cost.
  3. How to track usage and enforce soft and hard limits.
  4. How to monitor progress, check the state, and review a run.
  5. How to finish a run with a clear and structured report.

The Agent Lab includes a Budget tab with four meters: steps, tokens, time, and cost. The values use simple example rules, so every run produces the same numbers. The dashed line on each meter represents the soft limit. The end of the bar represents the hard limit.

Stop Conditions

A stop condition is a rule that ends the loop. Every agent should have more than one stop condition.

Goal Completion

Goal completion is the best way to stop. The goal has been achieved and verified. For a coding agent, this usually means that all tests pass.

Exit Signals

An exit signal is a message that tells the agent to stop, even though the goal has not been completed. For example, the agent may say "I am blocked and need help from a person," or a tool may report "the server is down for maintenance."

Interrupt Handling

An interrupt comes from outside the agent. For example, a person clicks Stop, or another system cancels the job.

The agent must stop cleanly. It should never report a partially completed task as successfully finished.

Three stop conditions

function shouldStop(state) {
  if (state.testsPass) return "stop: goal completed";
  if (state.lastAnswer && state.lastAnswer.startsWith("Stopped:")) return "stop: exit signal from the agent";
  if (state.interrupted) return "stop: interrupted by a person";
  return "keep going";
}

const states = [
  { testsPass: false },
  { testsPass: true },
  { testsPass: false, lastAnswer: "Stopped: the bug is in api/." },
  { testsPass: false, interrupted: true },
];

for (const state of states) console.log(shouldStop(state));

Expected output:

keep going
stop: goal completed
stop: exit signal from the agent
stop: interrupted by a person

Only the second stop condition results in a successful completion. The other two stops are also valid, but they must be reported as "not done".

An Interrupt Arrives

After 2 steps, an interrupt arrives. The run ends with the message "an interrupt stopped it". Open the final report under the result. It says NOT DONE because the goal was never verified.

Step Budgets

A budget is a limit on what the agent is allowed to use. Budgets help protect against agents that run longer than expected or consume too many resources.

Iteration Limits

An iteration limit, also called a step limit, is the maximum number of steps the loop can take. You have been using this limit since Lesson 1.

Token Limits

A token limit restricts the total number of tokens the model can read and generate. As you learned in Lesson 9, the input grows with every iteration, so token usage can increase quickly.

Time Limits

A time limit restricts how long a run is allowed to continue. Both model calls and slow-running tools consume time.

Cost Limits

A cost limit restricts how much money a run is allowed to spend. In most cases, cost is directly related to token usage.

Add up tokens, time and cost for a run

const steps = [
  { tokens: 220, ms: 2000 },
  { tokens: 290, ms: 1300 },
  { tokens: 400, ms: 1350 },
  { tokens: 430, ms: 2000 },
];
const pricePer1000 = 0.002;

const tokens = steps.reduce((sum, s) => sum + s.tokens, 0);
const seconds = steps.reduce((sum, s) => sum + s.ms, 0) / 1000;
const cost = (tokens / 1000) * pricePer1000;

console.log("Steps: " + steps.length);
console.log("Tokens: " + tokens);
console.log("Time: " + seconds + " s");
console.log("Cost: $" + cost.toFixed(4));

Expected output:

Steps: 4
Tokens: 1340
Time: 6.65 s
Cost: $0.0027

These are example prices and times. Real prices depend on the model being used. The important idea is the same: add up the usage from every step.

Budget Enforcement

Usage Tracking

Usage tracking means measuring and adding up resource usage after every step, similar to how a taxi meter tracks the cost of a ride. The Budget tab shows this information while the agent is running.

Soft Limits

A soft limit is a warning threshold, such as 80% of the total budget. When the agent reaches this point, the application adds a warning to the next result, such as "Finish soon." This gives the agent a chance to wrap up its work.

Hard Limits

A hard limit is a strict boundary. When the agent exceeds it, the application immediately stops the loop. No additional model calls are allowed after that point.

Soft warning first, then a hard stop

function checkBudget(used, limit, softShare) {
  if (used > limit) return "STOP (hard limit)";
  if (used >= limit * softShare) return "WARN (soft limit)";
  return "ok";
}

const tokensAfterEachStep = [220, 510, 910, 1360];
for (const used of tokensAfterEachStep) {
  console.log(used + " tokens: " + checkBudget(used, 1100, 0.8));
}

Expected output:

220 tokens: ok
510 tokens: ok
910 tokens: WARN (soft limit)
1360 tokens: STOP (hard limit)

The soft limit gives the agent one chance to finish. The hard limit makes sure it can never spend more than you allowed.

See both in the Agent Lab. The first run stays within its budget. The second run has a token budget that is too small.

Within budget

Hard token limit

In the first run, the Budget tab shows a soft warning at step 4, and all meters stay below their limits. In the second run, the warning appears at step 3, and the hard limit stops the run at step 4.

The report says NOT DONE, even if the code change might have worked. A run that is stopped by a budget limit is never considered complete.

Easy Way to Remember: A soft limit warns and a hard limit stops. Set both before the run begins.

Loop Monitoring

Monitoring means watching the loop while it is running, not just checking the result at the end.

Progress Checks

A progress check asks, "Did anything change?" every few steps. If the agent repeats the same action and gets the same result several times in a row, it is stuck.

Spot a stuck loop

function isStuck(log, window) {
  if (log.length < window) return false;
  const last = log.slice(-window);
  return last.every((entry) => entry === last[0]);
}

const healthy = ["run_tests: 2 failed", "read_file: ok", "write_file: saved", "run_tests: 0 failed"];
const stuck = ["run_tests: 2 failed", "list_files: 5 files", "list_files: 5 files", "list_files: 5 files"];

console.log("Healthy run stuck? " + isStuck(healthy, 3));
console.log("Second run stuck? " + isStuck(stuck, 3));

Expected output:

Healthy run stuck? false
Second run stuck? true

Progress Check Stops a Stuck Loop

The step limit is 15, but the run stops after only 3 steps. The progress check detects the same action and the same result three times in a row. This saves 12 unnecessary steps.

State Validation

State validation checks whether the agent's records are consistent. For example, the step count should match the number of log entries, and a run marked as "done" should have passing tests. You used the same idea for state validation in Lesson 4.

Runtime Analysis

Runtime analysis means examining how the agent used its time and tokens. For example: "70% of the time was spent on model calls." This helps identify what should be optimized.

Completion Management

When the loop ends, regardless of the reason, the agent should finish cleanly.

Output Generation

Output generation means creating the final result. This includes what was completed, what changed, and what work is still remaining.

Result Formatting

Result formatting means presenting the final result in a consistent structure. Using the same format every time makes it easier for both people and programs to read.

Session Closure

Session closure means ending the run completely. This includes stopping timers, saving logs, and making sure no tools are still running in the background.

A fixed report, then close the session

function report(run) {
  const outcome = run.stop === "final" && run.testsPass ? "DONE" : "NOT DONE";
  return [
    "Result: " + outcome,
    "Why it stopped: " + run.stop,
    "Steps: " + run.steps,
    "Files changed: " + (run.changed.join(", ") || "none"),
  ].join("\n");
}

const run = { stop: "budget", testsPass: true, steps: 4, changed: ["web/format.js"] };
console.log(report(run));

const session = Object.freeze({ id: "run-17", closed: true });
session.closed = false;
console.log("Session closed: " + session.closed);

Expected output:

Result: NOT DONE
Why it stopped: budget
Steps: 4
Files changed: web/format.js
Session closed: true

The tests pass, but the run stopped because it reached its budget limit, so the report still says NOT DONE. Object.freeze prevents anything from changing the closed session afterwards. The line that tries to reopen it has no effect.

Never let an agent decide whether a run succeeded based on its own words. Use facts instead: how the run ended and whether the tests passed. "Fixed!" in the final answer does not prove anything.

Common Mistakes

MistakeWrong IdeaCorrect IdeaWhat Goes Wrong
Only using a step limit"10 steps can't cost much."Limit tokens, time, and cost as well.Large inputs can make each step expensive.
No soft limit"The hard limit is enough."Warn the agent before the hard limit.The run may stop suddenly without a useful summary.
Trusting the agent's words"It said it is fixed."Decide using the stop reason and test results.A failed run may be reported as a success.
No progress check"It will stop when it reaches the limit."Stop the run after several repeated actions with no progress.Time, steps, and money are wasted.
Inconsistent final reports"Any format is fine."Use a single, consistent report format.People have to read every report in detail to understand it.

Exercises

Each exercise ends with a value on the last line. Press Check to compare it with the expected answer.

What to Remember

  • Stop the loop when the goal is completed, an exit signal is received, or an interrupt occurs. Only goal completion counts as a successful result.
  • Set budgets for steps, tokens, time, and cost.
  • A soft limit provides a warning. A hard limit immediately stops the run.
  • Check for progress regularly and stop a loop that is stuck.
  • End every run with a report in a fixed format and close the session properly.

Next: Using Tools, how an agent finds, checks and runs the right tool.