Haystack loop detection
ToolLoopDetectionHook checks a Haystack Agent before each LLM call. When it sees a loop, it can add a <system-reminder> to give the model a chance to recover. If the loop persists, the agent stops with exit_reason="tool_loop_detected".
Installation
The package requires Python 3.11 or newer and Haystack 3.2.0 or newer. Haystack 3.2.0 introduced the agent's stop_run state key, which the hook uses to end a persistent loop.
From a local checkout, run pip install .. After the first PyPI release, use the package name.
pip install haystack-loop-detection
Quickstart
This example runs locally. The mock generator keeps asking for the same job status, so the agent gets a warning after two calls and stops after the third.
from haystack.components.agents import Agent
from haystack.components.generators.chat import MockChatGenerator
from haystack.dataclasses import ChatMessage, ToolCall
from haystack.tools import tool
from haystack_integrations.hooks.loop_detection import ToolLoopDetectionHook
@tool
def job_status() -> str:
"""Return the current status of the job."""
return "pending"
request = ChatMessage.from_assistant(tool_calls=[ToolCall(tool_name="job_status", arguments={})])
agent = Agent(
chat_generator=MockChatGenerator(responses=request),
tools=[job_status],
hooks={"before_llm": [ToolLoopDetectionHook()]},
)
result = agent.run(messages=[ChatMessage.from_user("Check the job status.")])
assert result["exit_reason"] == "tool_loop_detected"
assert result["step_count"] == 3
Supported loops
The hook checks consecutive tool-calling steps in the current user turn. A new user request resets the history used for detection. Hook-generated reminders let the current turn continue.
| Pattern | What counts as one repetition |
|---|---|
| Exact repeat | One step with the same tool names and arguments. Argument key order and the order of parallel tool calls are ignored. |
| Ping-pong | One complete repeating sequence of steps. For example, A B A B counts as two cycles. |
| Consecutive errors | One consecutive step in which the same tool fails, even if its arguments change. |
Configuration
| Option | Default | Effect |
|---|---|---|
warn_threshold |
2 |
Add a reminder when this many repetitions are detected. Choose an integer from 2 up to (but excluding) stop_threshold, or None to disable warnings. |
stop_threshold |
3 |
Stop the agent at this many repetitions. Must be at least 2. |
max_cycle_length |
3 |
Longest ping-pong cycle to check, measured in tool-calling steps. Set to 1 to disable cycle detection. |
window_size |
20 |
Number of trailing tool-calling steps to consider. Must be at least stop_threshold. To stop a cycle of length k, the window must fit k * stop_threshold steps. |
detect_consecutive_errors |
True |
Count consecutive failures of the same tool. |
add_final_message |
False |
Append an assistant message explaining why the agent stopped. |
Serialization
ToolLoopDetectionHook.to_dict() stores its configuration and import path. Restore it with ToolLoopDetectionHook.from_dict(data). When the hook belongs to an agent, Agent.from_dict(agent.to_dict()) restores it through the installed haystack_integrations namespace. Haystack's default allowlist includes that namespace. If the agent also uses a tool defined in your application, make its module importable and add that trusted module to HAYSTACK_DESERIALIZATION_ALLOWLIST when restoring the agent.
Metadata
Release files for haystack-loop-detection 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| haystack_loop_detection-0.1.0.tar.gz | 14.5 kB | Without provenance | Details for haystack_loop_detection-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| haystack_loop_detection-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for haystack_loop_detection-0.1.0-py3-none-any.whl |
Total release size: 27.8 kB
Release files / haystack_loop_detection-0.1.0.tar.gz
| Download URL | haystack_loop_detection-0.1.0.tar.gz |
|---|---|
| Size | 14.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d3287ccd2d4fd850c3746ec1ff9c536aad20837b7b0169b6f42041e765e28299
|
|
BLAKE2b-256 checksum How to use checksums |
6f145d61533d25784feaf9099f998842211cdf143ef27807b61f481a32eb6c53
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.17 {"installer":{"name":"uv","version":"0.11.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / haystack_loop_detection-0.1.0-py3-none-any.whl
| Download URL | haystack_loop_detection-0.1.0-py3-none-any.whl |
|---|---|
| Size | 13.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
178001afa619af4ecbb9d9e29ed5a73c9c0f74157fb2070fa29f95014ad1eefa
|
|
BLAKE2b-256 checksum How to use checksums |
9fba72d3ef114c2039cca1f62a32d149394b4894340ea2a35d60524687bf1aef
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.17 {"installer":{"name":"uv","version":"0.11.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for haystack-loop-detection 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.