DEV Community

Poorna Reddy
Poorna Reddy

Posted on AI-assisted

Five Stop Conditions Every Production Claude Tool Loop Needs

A demo agent loop runs until the model says it is done. A production loop cannot work that way. Each tool call is a request to change something, and your code, not the model, decides when the loop stops.

Treat every tool call as an untrusted request

Claude returns a structured tool-use block: a tool name and arguments. Before anything runs, the application checks five things:

  1. Schema: the arguments have the right shape. A strict schema catches malformed calls.
  2. Identity and permission: the caller may use this tool for this task.
  3. Business rules: the live record is in the right state, amounts match, limits hold.
  4. Approval: actions above a threshold wait for a person.
  5. Idempotency: a retry cannot create a second payment, order or message.

Valid JSON that asks for an invalid action is still invalid. The schema checks shape; business validation checks meaning.

Return typed results

Send back a typed success or error, with fields the model can use safely. Separate two kinds of error:

  • Recoverable: for example AMOUNT_MISMATCH with the recorded amount. Claude may repair the request once.
  • Terminal: a permission failure, policy denial or unsafe content. Stop immediately.

A loop that returns free-text errors invites blind retries and invented fixes.

The five stop conditions

Write these in code:

  1. Done: the defined business outcome is complete.
  2. Waiting: a required human approval is missing. Pause; do not guess.
  3. Refused: a permission failure, policy denial or unsafe content.
  4. Retries used up: a small, fixed number of retries for transient or repairable errors.
  5. Budget exhausted: the maximum turns, tool calls, elapsed time, tokens or cost.

Leave out tools the task does not need

The simplest control is the tool you never give the agent. An accounts-payable agent that may request invoice approval does not need a payment tool. If payment is not on the allowlist, no prompt can make the loop release one.

Trace every run

Record the model version, inputs, tool calls, results and approvals for each run. When someone asks why the agent did something, the trace is the answer.

Go further

Top comments (0)