Add Stop Conditions, Retries, and Human Approval

Add Stop Conditions, Retries, and Human Approval

Published on

0

views

This article explains how to transition a small AI agent into a production-ready application by adding three essential operational controls: hard stop conditions to prevent infinite loops, bounded exponential retries for transient network errors, and explicit human-approval gates for side-effecting tools. These measures ensure predictable behavior, auditable execution, and strict safety without relying on model prompts.

A small agent that can call one tool is already useful. The moment that agent runs in production, three operational questions appear:

  • When does it stop?

  • What happens when a step fails transiently?

  • Which actions require a human to say yes before they execute?

This article adds those three controls to the minimal agent we built earlier. We keep the surface area small: one tool, explicit stop rules, a bounded retry for transient errors, and a human-approval gate for any side-effecting action. No open-ended loops, no hidden autonomy.

The Short Answer

Give the agent hard stop conditions (maximum steps, maximum tool calls, explicit termination signals). Retry only the failures that are known to be transient, and only a fixed number of times. Route any action that changes external state through a human-approval step before execution. Log every decision so you can later see why the agent stopped, retried, or waited for approval.

Low-angle shot of a backend engineer reviewing AI agent stop conditions and state check code on a laptop.

What Product Problem This Solves

Without stop conditions an agent can keep calling tools until it hits a token limit or a timeout. Without bounded retries a single network blip becomes a permanent failure. Without human approval a model-suggested side effect can run before anyone has reviewed it. Each of those gaps turns a controllable feature into an operational risk.

Adding the three controls keeps the agent useful while making its behavior predictable and auditable.

Minimal Working Extensions

We will extend the small-agent endpoint from the previous article. The changes are deliberately local.

1. Stop conditions

Python

MAX_MODEL_CALLS = 2          # first decision + optional final answer
MAX_TOOL_CALLS = 1           # hard limit
MAX_TOTAL_TOKENS = 2000      # rough ceiling for one request

class AgentState:
    def __init__(self):
        self.model_calls = 0
        self.tool_calls = 0
        self.total_tokens = 0
        self.messages = []
        self.stopped_reason: Optional[str] = None

    def can_continue(self) -> bool:
        if self.model_calls >= MAX_MODEL_CALLS:
            self.stopped_reason = "max_model_calls"
            return False
        if self.tool_calls >= MAX_TOOL_CALLS:
            self.stopped_reason = "max_tool_calls"
            return False
        if self.total_tokens >= MAX_TOTAL_TOKENS:
            self.stopped_reason = "max_tokens"
            return False
        return True

Every time the agent is about to make another model call or tool call it checks can_continue(). If the check fails, the request ends with a clear stopped_reason. The model never gets an unbounded loop.

2. Bounded retries for transient failures

Python

from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
from openai import APITimeoutError, APIConnectionError, RateLimitError

TRANSIENT = (APITimeoutError, APIConnectionError, RateLimitError)

@retry(
    retry=retry_if_exception_type(TRANSIENT),
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=0.5, min=0.5, max=4),
    reraise=True,
)
def call_model_with_retry(client, **kwargs):
    return client.chat.completions.create(**kwargs)

Only network-level and rate-limit errors are retried. Validation failures, unknown tools, and business-rule rejections are not retried—they are permanent for that request. Three attempts with exponential back-off are enough for most transient blips; more attempts usually just burn tokens and latency.

3. Human approval for side-effecting tools

Not every tool is a pure lookup. When a tool would change external state (send an email, cancel an order, write to a production database) the agent must not execute it automatically.

Python

class ApprovalStatus(str, Enum):
    not_required = "not_required"
    pending = "pending"
    approved = "approved"
    rejected = "rejected"

# In the tool registry
TOOL_REGISTRY = {
    "fetch_order_status": {
        "function": fetch_order_status,
        "args_model": OrderStatusArgs,
        "description": "...",
        "allowed": True,
        "requires_approval": False,          # pure lookup
    },
    "cancel_order": {
        "function": cancel_order,
        "args_model": CancelOrderArgs,
        "description": "...",
        "allowed": True,
        "requires_approval": True,           # side effect
    },
}

When the model requests a tool marked requires_approval=True, the endpoint:

  1. Validates the arguments exactly as before.

  2. Writes a pending approval record (task id, tool name, arguments, timestamp).

  3. Returns a response with status="pending_approval" and the approval id.

  4. Does not execute the function.

A separate, authenticated endpoint lets a human (or an internal review system) approve or reject the pending action. Only after explicit approval does the original function run, and only then is the final answer generated.

Python

@app.post("/v1/approvals/{approval_id}/decide")
async def decide_approval(
    approval_id: str,
    decision: Literal["approve", "reject"],
    db: AsyncSession = Depends(get_db),
    # auth dependency omitted for brevity
):
    record = await get_approval_record(db, approval_id)
    if not record or record.status != "pending":
        raise HTTPException(status_code=404, detail="Approval not found or already decided")

    if decision == "reject":
        record.status = "rejected"
        await db.commit()
        return {"status": "rejected"}

    # decision == "approve"
    meta = TOOL_REGISTRY[record.tool_name]
    args = meta["args_model"].model_validate(record.arguments)
    result = meta["function"](**args.model_dump())
    record.status = "approved"
    record.result = result
    await db.commit()

    # Optionally trigger the final-answer generation here or leave it to the caller
    return {"status": "approved", "result": result}

The agent itself never bypasses this gate.

Putting the Pieces Together

The main agent handler now looks roughly like this:

  1. Initialize AgentState.

  2. While state.can_continue():

    • Call the model (with retry wrapper).

    • Update token counts and model-call counter.

    • If the model returns a final answer → stop with status="answered".

    • If the model requests a tool:

      • Validate name and arguments.

      • If requires_approval → create pending record, stop with status="pending_approval".

      • Else execute (with its own narrow retry if the tool itself is idempotent and transient-safe).

      • Increment tool-call counter.

      • Feed the result back for the optional final answer.

  3. If the loop exits because a stop condition was hit, return the last known state plus stopped_reason.

Every path leaves a clear status and a log line.

Why These Limits Belong in Application Code

Stop conditions, retry policies, and approval requirements are product and safety decisions. They do not belong in the prompt. Prompts can be ignored or creatively reinterpreted; a counter and a database flag cannot. Keeping the controls in ordinary code makes them testable, auditable, and changeable without re-prompting the model.

Wide-angle shot of an engineer testing agent limits and audit logs in a dim, modern development environment.

What Was Tested and What Remains Uncertain

I tested the stop conditions by forcing low limits and confirming the agent halted with the expected reason. Transient errors were simulated and retried the configured number of times. Approval-gated tools created pending records and refused to execute until an explicit approve call arrived.

I have not measured the distribution of stop reasons under real traffic, nor have I tested every combination of concurrent approvals and retries. Exact rate-limit behavior, token accounting across retries, and the reliability of the underlying tool functions must still be verified against current official documentation and your own infrastructure. Human-approval latency is a product variable; the code only guarantees that the side effect cannot run before the approval arrives.

When a Simpler Approach Is Enough

If the agent never performs side effects, the approval gate can be omitted. If every failure is permanent, the retry wrapper can be omitted. If the workflow is truly single-step, go back to the deterministic path. Add each control only when the risk it addresses is real.

Before adding more tools or longer loops, see whether the current stop conditions, retries, and approval gate already keep the agent safe and useful. The extra complexity has to earn its place.

Practical Conclusion

Stop conditions, bounded retries, and human approval turn a small agent from a demo into something you can operate. The model may still propose the next action; your application decides when to stop, when to retry, and when a human must say yes.

Start with the smallest version that can answer the product question. In this case the question is “Can I keep the agent from running forever, recovering from blips, or executing side effects without review?” The controls above are that version.

Build real applications. Verify every step.

Last updated:

Share:

Leave a comment

Related Articles

Do You Need an Agent? Start with a Deterministic Workflow
Agents & Automation |

Do You Need an Agent? Start with a Deterministic Workflow

This article argues that most AI features do not require complex, unpredictable agent loops. Instead, it advocates for starting with a deterministic workflow—a clear, sequential set of steps combining narrow model calls, ordinary Python validation, explicit error handling, and robust logging. This approach ensures lower latency, predictable token costs, and easier debugging before adding agentic complexity.

0
Build a Small GPT-6.1 Sol Agent with One Verified Tool
Agents & Automation |

Build a Small GPT-6.1 Sol Agent with One Verified Tool

This article demonstrates how to build a minimal, highly secure AI agent within a FastAPI service using the GPT-6.1 Sol model. It covers registering a single verified tool, enforcing hard stop conditions, validating arguments with Pydantic, and managing explicit permissions. This ensures the model only proposes actions while your application retains full control over execution and termination.

0