tool-loop-guard
tool-loop-guard

how tool-loop-guard fits in

Install

consolepip install tool-loop-guard

Use

pythonfrom tool_loop_guard import LoopDetected, LoopGuard

guard = LoopGuard(max_repeats=3, cycle_length=4)

def call_tool(name, arguments, tool):
    decision = guard.observe(name, arguments)
    if decision.action == "stop":
        return f"Stopped: {decision.reason}. Change your approach or ask the user."
    if decision.action == "warn":
        return f"{decision.reason}; you are repeating yourself."
    return tool(**arguments)

Or let it raise:

pythontry:
    guard.check("search", {"q": "python"})
except LoopDetected as error:
    error.decision.action, error.decision.reason
    # ('stop', 'repeating cycle of 2 calls: read ↔ search')

Wrapping a tool registry, which is the shape a LangGraph or Deep Agents middleware takes:

pythondef wrap(tool, name, guard):
    if asyncio.iscoroutinefunction(tool):
        async def guarded(**arguments):
            decision = guard.observe(name, arguments)
            if decision.action == "stop":
                return {"error": decision.reason, "action": "stop"}
            return await tool(**arguments)
    else:
        def guarded(**arguments):
            decision = guard.observe(name, arguments)
            if decision.action == "stop":
                return {"error": decision.reason, "action": "stop"}
            return tool(**arguments)
    return guarded

Why the signature works

signature(name, arguments) is order-insensitive: {"a": 1, "b": 2} and {"b": 2, "a": 1} are the same call, nested dicts are canonicalised, surrounding whitespace in strings is dropped, and strings longer than 200 characters are truncated before hashing — a model that re-emits a 4 000 character file body as an argument is still caught. The name is part of the signature, so write_file and read_file with the same path are different calls.

Rules

setting default meaning
max_repeats3the count at which an identical call stops the run
cycle_length4the longest period looked for in A B A B
window40how many recent calls are kept; must be ≥ 2 × cycle_length

Limits

until it returns, so pair it with a token budget.

different signatures; normalise the arguments before calling observe if you have aliases like that.

Development

consolepython -m venv .venv
.venv/bin/pip install -e ".[test]"
.venv/bin/pytest

The suite covers every line of the package (pytest --cov --cov-branch), and the examples in the docstrings run as tests through --doctest-modules.

License

MIT.

Other libraries here

One problem each, standard library only, no runtime dependencies.