Metadata-Version: 2.5
Name: haystack-loop-detection
Version: 0.1.0
Summary: Detect repeated tool calls and stop persistent loops in Haystack agents.
Project-URL: Homepage, https://github.com/LowmistLMT/haystack-loop-detection
Project-URL: Repository, https://github.com/LowmistLMT/haystack-loop-detection
Author: LowmistLMT
License-Expression: Apache-2.0
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: haystack-ai>=3.2.0
Description-Content-Type: text/markdown

# 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.

```sh
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.

```python
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.
