Module 3: Bounded Agents in Production
Stop Conditions, Loop Ceilings & Guardrails
How to prevent infinite execution loops, token drain, and dangerous edge-case behaviors with deterministic guards.
Without hard ceilings, agents can easily enter recursive loops where the model repeatedly tries the same failing tool call until rate limits or credit cards are exhausted.
The Iteration Cap Primitive
Every agent loop must be governed by an explicit maximum iteration parameter:
MAX_TURNS = 8
async def run_agent_loop(initial_prompt: str):
messages = [{"role": "user", "content": initial_prompt}]
for turn in range(MAX_TURNS):
response = await client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=REGISTERED_TOOLS
)
if not response.choices[0].message.tool_calls:
# Model has reached final answer
return response.choices[0].message.content
# Execute tool calls and append results
await execute_and_append_tools(response, messages)
# Hard exit if ceiling reached without completion
raise AgentExecutionError("Loop ceiling exceeded: Agent failed to reach conclusion in 8 turns.")
Repeat Tool-Call Detection
A common failure mode is an agent repeating the exact same tool call with identical arguments 3 times in a row. Implement a trajectory hash check:
- Maintain a set of
(tool_name, argument_hash)for the current session. - If the model repeats the exact signature twice, inject a system message warning: “You have attempted this identical action before and it failed. Choose an alternative approach or ask the user for clarification.”
Output Guardrails with Llama-Guard / NeMo
Before delivering text to end users, pass agent outputs through deterministic policy checks:
- PII Filtering: Scrub Social Security Numbers, API keys, and email addresses.
- Jailbreak Interception: Verify the agent did not regurgitate hidden system instructions.
Continue to Human-in-the-Loop Workflows.
Was this page helpful?