Hey everyone,
If you’ve ever come back to an AI agent stuck repeating the same action or message, you’re not alone.
I use a simple Two-Tier Loop Prevention Guardrail that combines platform safeguards with behavioral instructions to stop repetitive cycles.
Here’s how it works:
Tier 1: The Platform Safety Net (hooks.json)
We configure a hard limit at the execution manager level to kill the session if it runs too many consecutive automated turns.
-
Path:
~/.gemini/config/hooks.json(or your platform’s hooks directory) -
Configuration:
{ "max_consecutive_replies": 3 } -
Why it works: If the agent tries to talk to itself or repeat turns more than 3 times without human input, the execution manager forcibly terminates the session.
Tier 2: The Behavioral Instruction Layer (safeguards.md)
We define rules in the agent’s instructions (like a project rules markdown file) so it actively monitors its own history and stops before the platform manager has to kill it.
-
The Rule:
### Repetitive Response & Loop Prevention * **No Periodic Repetition**: Do not output the same status, instructions, warnings, or message sequences across multiple turns. * **Self-Termination Guard**: If you observe that your previous 2 turns generated identical or highly similar messages, instructions, or planning statuses, immediately halt execution and output a single message asking the user for manual guidance. * **Duplicate Tool Calls**: Do not execute the same tool with identical arguments more than twice in the same conversation thread.
By combining these two tiers, you get a polite behavioral self-halt at 2 loops, and a hard engine-level cutoff at 3 loops if the agent fails to self-police.
Prompt to Ask Your Agent to Set This Up for You:
Copy and paste this prompt into your agent chat to have it set up the same guardrails automatically:
Please configure a two-tier loop prevention guardrail for my environment:
1. Create or update the local config file `~/.gemini/config/hooks.json` to define a strict loop stopping condition:
{
"max_consecutive_replies": 3
}
2. Add a section to my project's agent rules or safeguards markdown file instructing agents to self-police:
### Repetitive Response & Loop Prevention
* **No Periodic Repetition**: Do not output the same status, instructions, warnings, or message sequences across multiple turns.
* **Self-Termination Guard**: If you observe that your previous 2 turns generated identical or highly similar messages, instructions, or planning statuses, immediately halt execution and output a single message asking the user for manual guidance.
* **Duplicate Tool Calls**: Do not execute the same tool with identical arguments more than twice in the same conversation thread.
.
.
.
.
.
For Google folks:
- If anything is wrong or could be improved, feel free to let me know.
- If this post is relevant to the current issues, feel free to pin it or use it however you think is appropriate.