haystack-loop-detection 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .venv/
5
+ venv/
6
+ .hatch/
7
+ build/
8
+ dist/
9
+ .mypy_cache/
10
+ .pytest_cache/
11
+ .ruff_cache/
12
+ .coverage
13
+ htmlcov/
14
+ .DS_Store
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2021 deepset GmbH
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.5
2
+ Name: haystack-loop-detection
3
+ Version: 0.1.0
4
+ Summary: Detect repeated tool calls and stop persistent loops in Haystack agents.
5
+ Project-URL: Homepage, https://github.com/LowmistLMT/haystack-loop-detection
6
+ Project-URL: Repository, https://github.com/LowmistLMT/haystack-loop-detection
7
+ Author: LowmistLMT
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.11
11
+ Requires-Dist: haystack-ai>=3.2.0
12
+ Description-Content-Type: text/markdown
13
+
14
+ # Haystack loop detection
15
+
16
+ `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"`.
17
+
18
+ ## Installation
19
+
20
+ 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.
21
+
22
+ From a local checkout, run `pip install .`. After the first PyPI release, use the package name.
23
+
24
+ ```sh
25
+ pip install haystack-loop-detection
26
+ ```
27
+
28
+ ## Quickstart
29
+
30
+ 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.
31
+
32
+ ```python
33
+ from haystack.components.agents import Agent
34
+ from haystack.components.generators.chat import MockChatGenerator
35
+ from haystack.dataclasses import ChatMessage, ToolCall
36
+ from haystack.tools import tool
37
+ from haystack_integrations.hooks.loop_detection import ToolLoopDetectionHook
38
+
39
+
40
+ @tool
41
+ def job_status() -> str:
42
+ """Return the current status of the job."""
43
+ return "pending"
44
+
45
+
46
+ request = ChatMessage.from_assistant(tool_calls=[ToolCall(tool_name="job_status", arguments={})])
47
+ agent = Agent(
48
+ chat_generator=MockChatGenerator(responses=request),
49
+ tools=[job_status],
50
+ hooks={"before_llm": [ToolLoopDetectionHook()]},
51
+ )
52
+ result = agent.run(messages=[ChatMessage.from_user("Check the job status.")])
53
+ assert result["exit_reason"] == "tool_loop_detected"
54
+ assert result["step_count"] == 3
55
+ ```
56
+
57
+ ## Supported loops
58
+
59
+ 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.
60
+
61
+ | Pattern | What counts as one repetition |
62
+ | --- | --- |
63
+ | Exact repeat | One step with the same tool names and arguments. Argument key order and the order of parallel tool calls are ignored. |
64
+ | Ping-pong | One complete repeating sequence of steps. For example, `A B A B` counts as two cycles. |
65
+ | Consecutive errors | One consecutive step in which the same tool fails, even if its arguments change. |
66
+
67
+ ## Configuration
68
+
69
+ | Option | Default | Effect |
70
+ | --- | --- | --- |
71
+ | `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. |
72
+ | `stop_threshold` | `3` | Stop the agent at this many repetitions. Must be at least 2. |
73
+ | `max_cycle_length` | `3` | Longest ping-pong cycle to check, measured in tool-calling steps. Set to 1 to disable cycle detection. |
74
+ | `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. |
75
+ | `detect_consecutive_errors` | `True` | Count consecutive failures of the same tool. |
76
+ | `add_final_message` | `False` | Append an assistant message explaining why the agent stopped. |
77
+
78
+ ## Serialization
79
+
80
+ `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.
@@ -0,0 +1,67 @@
1
+ # Haystack loop detection
2
+
3
+ `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"`.
4
+
5
+ ## Installation
6
+
7
+ 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.
8
+
9
+ From a local checkout, run `pip install .`. After the first PyPI release, use the package name.
10
+
11
+ ```sh
12
+ pip install haystack-loop-detection
13
+ ```
14
+
15
+ ## Quickstart
16
+
17
+ 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.
18
+
19
+ ```python
20
+ from haystack.components.agents import Agent
21
+ from haystack.components.generators.chat import MockChatGenerator
22
+ from haystack.dataclasses import ChatMessage, ToolCall
23
+ from haystack.tools import tool
24
+ from haystack_integrations.hooks.loop_detection import ToolLoopDetectionHook
25
+
26
+
27
+ @tool
28
+ def job_status() -> str:
29
+ """Return the current status of the job."""
30
+ return "pending"
31
+
32
+
33
+ request = ChatMessage.from_assistant(tool_calls=[ToolCall(tool_name="job_status", arguments={})])
34
+ agent = Agent(
35
+ chat_generator=MockChatGenerator(responses=request),
36
+ tools=[job_status],
37
+ hooks={"before_llm": [ToolLoopDetectionHook()]},
38
+ )
39
+ result = agent.run(messages=[ChatMessage.from_user("Check the job status.")])
40
+ assert result["exit_reason"] == "tool_loop_detected"
41
+ assert result["step_count"] == 3
42
+ ```
43
+
44
+ ## Supported loops
45
+
46
+ 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.
47
+
48
+ | Pattern | What counts as one repetition |
49
+ | --- | --- |
50
+ | Exact repeat | One step with the same tool names and arguments. Argument key order and the order of parallel tool calls are ignored. |
51
+ | Ping-pong | One complete repeating sequence of steps. For example, `A B A B` counts as two cycles. |
52
+ | Consecutive errors | One consecutive step in which the same tool fails, even if its arguments change. |
53
+
54
+ ## Configuration
55
+
56
+ | Option | Default | Effect |
57
+ | --- | --- | --- |
58
+ | `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. |
59
+ | `stop_threshold` | `3` | Stop the agent at this many repetitions. Must be at least 2. |
60
+ | `max_cycle_length` | `3` | Longest ping-pong cycle to check, measured in tool-calling steps. Set to 1 to disable cycle detection. |
61
+ | `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. |
62
+ | `detect_consecutive_errors` | `True` | Count consecutive failures of the same tool. |
63
+ | `add_final_message` | `False` | Append an assistant message explaining why the agent stopped. |
64
+
65
+ ## Serialization
66
+
67
+ `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.
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "haystack-loop-detection"
7
+ version = "0.1.0"
8
+ description = "Detect repeated tool calls and stop persistent loops in Haystack agents."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "LowmistLMT" }]
14
+ dependencies = ["haystack-ai>=3.2.0"]
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/LowmistLMT/haystack-loop-detection"
18
+ Repository = "https://github.com/LowmistLMT/haystack-loop-detection"
19
+
20
+ [tool.hatch.build.targets.wheel]
21
+ packages = ["src/haystack_integrations"]
22
+
23
+ [tool.hatch.build.targets.sdist]
24
+ include = ["/src", "/tests", "/LICENSE", "/README.md", "/pyproject.toml"]
25
+
26
+ [tool.hatch.envs.test]
27
+ dependencies = ["pytest", "pytest-asyncio", "mypy", "ruff"]
28
+
29
+ [tool.hatch.envs.test.scripts]
30
+ unit = "pytest {args:tests}"
31
+
32
+ [tool.pytest.ini_options]
33
+ asyncio_default_fixture_loop_scope = "function"
34
+
35
+ [tool.mypy]
36
+ python_version = "3.12"
37
+ mypy_path = "src"
38
+ explicit_package_bases = true
39
+ check_untyped_defs = true
40
+
41
+ [tool.ruff]
42
+ target-version = "py311"
43
+ line-length = 120
44
+
45
+ [tool.ruff.lint]
46
+ select = ["E4", "E7", "E9", "F", "I", "B", "SIM"]
@@ -0,0 +1,8 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from haystack_integrations.hooks.loop_detection.detector import LoopDetectionResult, LoopKind
6
+ from haystack_integrations.hooks.loop_detection.hooks import ToolLoopDetectionHook
7
+
8
+ __all__ = ["LoopDetectionResult", "LoopKind", "ToolLoopDetectionHook"]
@@ -0,0 +1,266 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import hashlib
6
+ import json
7
+ from collections.abc import Sequence
8
+ from dataclasses import dataclass
9
+ from typing import Any, Literal
10
+
11
+ from haystack.dataclasses import ChatMessage, ChatRole
12
+
13
+ SYSTEM_REMINDER_META_KEY = "system_reminder"
14
+
15
+ LoopKind = Literal["exact_repeat", "ping_pong", "consecutive_error"]
16
+ InterventionAction = Literal["warn", "stop"]
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class LoopDetectionResult:
21
+ """
22
+ Structured description of a detected tool-calling loop in an Agent conversation.
23
+
24
+ :param kind: Category of loop detected: `"exact_repeat"`, `"ping_pong"`, or `"consecutive_error"`.
25
+ :param tool_names: Tool names involved in the detected loop.
26
+ :param repetitions: Number of consecutive repetitions, completed cycles, or consecutive tool errors observed.
27
+ :param cycle_length: Number of tool-call steps per cycle (`1` for exact repeats and consecutive errors, `>= 2` for
28
+ ping-pong cycles).
29
+ :param detail: Human-readable summary of the detected loop.
30
+ """
31
+
32
+ kind: LoopKind
33
+ tool_names: tuple[str, ...]
34
+ repetitions: int
35
+ cycle_length: int
36
+ detail: str
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class _ToolStep:
41
+ """Normalized record of one assistant tool-calling turn and its immediately following tool errors."""
42
+
43
+ call_signature: str
44
+ tool_names: tuple[str, ...]
45
+ errored_tools: tuple[str, ...]
46
+
47
+
48
+ def _canonical_json(value: Any) -> str:
49
+ """Serialize arbitrary tool arguments deterministically, independent of dictionary key order."""
50
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)
51
+
52
+
53
+ def _step_signature(message: ChatMessage) -> tuple[str, tuple[str, ...]]:
54
+ """
55
+ Compute a canonical SHA-256 signature and sorted distinct tool names for an assistant tool-call message.
56
+
57
+ Sorting the `(tool_name, canonical_arguments)` pairs ensures that parallel tool calls issued in a different order
58
+ produce the same signature.
59
+ """
60
+ normalized_calls = sorted((tc.tool_name, _canonical_json(tc.arguments)) for tc in message.tool_calls)
61
+ digest = hashlib.sha256(_canonical_json(normalized_calls).encode("utf-8")).hexdigest()
62
+ tool_names = tuple(sorted({tc.tool_name for tc in message.tool_calls}))
63
+ return digest, tool_names
64
+
65
+
66
+ def _is_system_reminder(message: ChatMessage) -> bool:
67
+ return message.is_from(role=ChatRole.USER) and SYSTEM_REMINDER_META_KEY in message.meta
68
+
69
+
70
+ def _current_turn_start(messages: Sequence[ChatMessage]) -> int:
71
+ """
72
+ Return the index after the latest non-reminder user message.
73
+
74
+ In multi-turn conversations, tool calls from earlier user turns belong to prior tasks and should not trigger loop
75
+ detection for the current turn. Synthetic `<system-reminder>` user messages injected by hooks are skipped so they
76
+ do not reset the active loop window.
77
+ """
78
+ for idx in range(len(messages) - 1, -1, -1):
79
+ msg = messages[idx]
80
+ if msg.is_from(role=ChatRole.USER) and not _is_system_reminder(msg):
81
+ return idx + 1
82
+ return 0
83
+
84
+
85
+ def _extract_tool_steps(messages: Sequence[ChatMessage], *, window_size: int) -> list[_ToolStep]:
86
+ """Extract normalized tool-calling steps from the active conversation turn, capped to the trailing window."""
87
+ start = _current_turn_start(messages)
88
+ steps: list[_ToolStep] = []
89
+
90
+ current_sig: str | None = None
91
+ current_tools: tuple[str, ...] = ()
92
+ current_errors: set[str] = set()
93
+
94
+ for msg in messages[start:]:
95
+ if msg.is_from(role=ChatRole.ASSISTANT) and msg.tool_calls:
96
+ if current_sig is not None:
97
+ steps.append(
98
+ _ToolStep(
99
+ call_signature=current_sig,
100
+ tool_names=current_tools,
101
+ errored_tools=tuple(sorted(current_errors)),
102
+ )
103
+ )
104
+ current_sig, current_tools = _step_signature(msg)
105
+ current_errors = set()
106
+ elif current_sig is not None and (result := msg.tool_call_result) is not None and result.error:
107
+ current_errors.add(result.origin.tool_name)
108
+
109
+ if current_sig is not None:
110
+ steps.append(
111
+ _ToolStep(call_signature=current_sig, tool_names=current_tools, errored_tools=tuple(sorted(current_errors)))
112
+ )
113
+
114
+ return steps[-window_size:]
115
+
116
+
117
+ def _detect_exact_repeat(steps: Sequence[_ToolStep]) -> LoopDetectionResult | None:
118
+ """Detect consecutive trailing steps that issue identical tool calls."""
119
+ if len(steps) < 2:
120
+ return None
121
+
122
+ target_sig = steps[-1].call_signature
123
+ count = 1
124
+ for idx in range(len(steps) - 2, -1, -1):
125
+ if steps[idx].call_signature == target_sig:
126
+ count += 1
127
+ else:
128
+ break
129
+
130
+ if count < 2:
131
+ return None
132
+
133
+ tool_names = steps[-1].tool_names
134
+ tools_label = ", ".join(tool_names)
135
+ return LoopDetectionResult(
136
+ kind="exact_repeat",
137
+ tool_names=tool_names,
138
+ repetitions=count,
139
+ cycle_length=1,
140
+ detail=f"identical tool call(s) [{tools_label}] repeated {count} times in a row",
141
+ )
142
+
143
+
144
+ def _detect_ping_pong(steps: Sequence[_ToolStep], *, max_cycle_length: int) -> LoopDetectionResult | None:
145
+ """Detect trailing alternating tool-call cycles of length `2..max_cycle_length`."""
146
+ n_steps = len(steps)
147
+ upper_k = min(max_cycle_length, n_steps // 2)
148
+ if upper_k < 2:
149
+ return None
150
+
151
+ best: LoopDetectionResult | None = None
152
+ for cycle_len in range(2, upper_k + 1):
153
+ pattern = [step.call_signature for step in steps[-cycle_len:]]
154
+ # A constant pattern is already captured by `_detect_exact_repeat`.
155
+ if len(set(pattern)) == 1:
156
+ continue
157
+
158
+ cycles = 1
159
+ pos = n_steps - 2 * cycle_len
160
+ while pos >= 0:
161
+ candidate = [step.call_signature for step in steps[pos : pos + cycle_len]]
162
+ if candidate == pattern:
163
+ cycles += 1
164
+ pos -= cycle_len
165
+ else:
166
+ break
167
+
168
+ if cycles >= 2 and (best is None or cycles > best.repetitions):
169
+ seen: list[str] = []
170
+ for step in steps[-cycle_len:]:
171
+ for name in step.tool_names:
172
+ if name not in seen:
173
+ seen.append(name)
174
+ tool_names = tuple(seen)
175
+ tools_label = " -> ".join(tool_names)
176
+ best = LoopDetectionResult(
177
+ kind="ping_pong",
178
+ tool_names=tool_names,
179
+ repetitions=cycles,
180
+ cycle_length=cycle_len,
181
+ detail=f"alternating {cycle_len}-step tool cycle ({tools_label}) repeated {cycles} times",
182
+ )
183
+
184
+ return best
185
+
186
+
187
+ def _detect_consecutive_errors(steps: Sequence[_ToolStep]) -> LoopDetectionResult | None:
188
+ """Detect a tool returning errors across consecutive trailing steps, even when arguments vary."""
189
+ if len(steps) < 2 or not steps[-1].errored_tools:
190
+ return None
191
+
192
+ best_tool = ""
193
+ best_count = 0
194
+ for tool_name in steps[-1].errored_tools:
195
+ count = 1
196
+ for idx in range(len(steps) - 2, -1, -1):
197
+ if tool_name in steps[idx].errored_tools:
198
+ count += 1
199
+ else:
200
+ break
201
+ if count > best_count:
202
+ best_count = count
203
+ best_tool = tool_name
204
+
205
+ if best_count < 2:
206
+ return None
207
+
208
+ return LoopDetectionResult(
209
+ kind="consecutive_error",
210
+ tool_names=(best_tool,),
211
+ repetitions=best_count,
212
+ cycle_length=1,
213
+ detail=f"tool '{best_tool}' failed {best_count} times in a row",
214
+ )
215
+
216
+
217
+ def detect_tool_loop(
218
+ messages: Sequence[ChatMessage],
219
+ *,
220
+ warn_threshold: int | None,
221
+ stop_threshold: int,
222
+ max_cycle_length: int,
223
+ window_size: int,
224
+ detect_consecutive_errors: bool,
225
+ ) -> tuple[LoopDetectionResult | None, InterventionAction | None]:
226
+ """
227
+ Analyze the active Agent conversation for tool-calling loops and return the triggered intervention.
228
+
229
+ Stop-level triggers take precedence over warn-level triggers. Within the same severity level, candidates are
230
+ evaluated in deterministic order: exact repeat, ping-pong cycle, then consecutive tool errors.
231
+
232
+ :param messages: Full Agent message history, oldest to newest.
233
+ :param warn_threshold: Repetition threshold for emitting a warning reminder, or `None` to disable warnings.
234
+ :param stop_threshold: Repetition threshold for stopping the Agent run.
235
+ :param max_cycle_length: Maximum cycle length to inspect for alternating ping-pong loops (`1` disables it).
236
+ :param window_size: Maximum number of trailing tool-calling steps to inspect.
237
+ :param detect_consecutive_errors: Whether to detect consecutive errors from the same tool.
238
+ :returns: A `(result, action)` tuple where `action` is `"stop"`, `"warn"`, or `None` when no threshold is met.
239
+ """
240
+ steps = _extract_tool_steps(messages=messages, window_size=window_size)
241
+ if len(steps) < 2:
242
+ return None, None
243
+
244
+ candidates: list[LoopDetectionResult] = []
245
+ exact = _detect_exact_repeat(steps)
246
+ if exact is not None:
247
+ candidates.append(exact)
248
+ if max_cycle_length >= 2:
249
+ ping_pong = _detect_ping_pong(steps, max_cycle_length=max_cycle_length)
250
+ if ping_pong is not None:
251
+ candidates.append(ping_pong)
252
+ if detect_consecutive_errors:
253
+ errors = _detect_consecutive_errors(steps)
254
+ if errors is not None:
255
+ candidates.append(errors)
256
+
257
+ for candidate in candidates:
258
+ if candidate.repetitions >= stop_threshold:
259
+ return candidate, "stop"
260
+
261
+ if warn_threshold is not None:
262
+ for candidate in candidates:
263
+ if candidate.repetitions >= warn_threshold:
264
+ return candidate, "warn"
265
+
266
+ return None, None
@@ -0,0 +1,184 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any
6
+
7
+ from haystack import default_from_dict, default_to_dict, logging
8
+ from haystack.components.agents.state import State
9
+ from haystack.dataclasses import ChatMessage
10
+
11
+ from haystack_integrations.hooks.loop_detection.detector import (
12
+ SYSTEM_REMINDER_META_KEY,
13
+ LoopDetectionResult,
14
+ detect_tool_loop,
15
+ )
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ _EXIT_REASON_TOOL_LOOP = "tool_loop_detected"
20
+ _LOOP_WARNING_META_KEY = "tool_loop_warning"
21
+
22
+ _FINAL_MESSAGE_TEMPLATE = "The Agent stopped because a tool-calling loop was detected ({detail})."
23
+
24
+ _WARNING_TEMPLATE = (
25
+ "Loop detection warning: {detail}. "
26
+ "Do not repeat the same failing or redundant tool calls; try a different approach or provide your final answer "
27
+ "with the information you already have."
28
+ )
29
+
30
+
31
+ def _warning_key(result: LoopDetectionResult) -> str:
32
+ """Build a deterministic deduplication key for a loop warning reminder."""
33
+ return f"{result.kind}:{result.repetitions}:{','.join(result.tool_names)}"
34
+
35
+
36
+ class ToolLoopDetectionHook:
37
+ """
38
+ Detect repetitive or stalled tool-calling loops and nudge or stop the Agent.
39
+
40
+ This `before_llm` hook inspects the conversation history in `state.data["messages"]` before each LLM call without
41
+ keeping mutable state on the hook instance, so a single instance can be safely shared across concurrent Agent runs.
42
+
43
+ It detects three loop patterns within the active user turn:
44
+ - **Exact repeats**: consecutive steps issuing the exact same tool calls and arguments.
45
+ - **Ping-pong cycles**: alternating tool-call sequences of length `2..max_cycle_length` (e.g. `A -> B -> A -> B`).
46
+ - **Consecutive errors**: the same tool returning errors across consecutive steps, even when arguments vary.
47
+
48
+ Intervention happens in two stages:
49
+ 1. When repetitions reach `warn_threshold` (if set), a `<system-reminder>` user message marked with
50
+ `meta={"system_reminder": True}` is appended so the model can change strategy and recover.
51
+ 2. When repetitions reach `stop_threshold`, the hook sets `state.set("stop_run", "tool_loop_detected")`, ending the
52
+ run cleanly before spending another LLM call.
53
+
54
+ Pass the hook in the `Agent` constructor's `hooks` argument:
55
+
56
+ ```python
57
+ from haystack_integrations.hooks.loop_detection import ToolLoopDetectionHook
58
+
59
+ hooks = {"before_llm": [ToolLoopDetectionHook()]}
60
+ ```
61
+ """
62
+
63
+ allowed_hook_points = ("before_llm",)
64
+
65
+ def __init__(
66
+ self,
67
+ *,
68
+ warn_threshold: int | None = 2,
69
+ stop_threshold: int = 3,
70
+ max_cycle_length: int = 3,
71
+ window_size: int = 20,
72
+ detect_consecutive_errors: bool = True,
73
+ add_final_message: bool = False,
74
+ ) -> None:
75
+ """
76
+ Create a tool-loop detection hook.
77
+
78
+ :param warn_threshold: Number of consecutive repetitions, completed ping-pong cycles, or consecutive tool
79
+ errors at which a `<system-reminder>` warning is injected. Set to `None` to disable reminders and only stop
80
+ at `stop_threshold`. Must be at least 2 and strictly less than `stop_threshold` when provided.
81
+ :param stop_threshold: Number of consecutive repetitions, completed ping-pong cycles, or consecutive tool
82
+ errors at which the Agent is stopped with `exit_reason="tool_loop_detected"`. Must be at least 2.
83
+ :param max_cycle_length: Maximum cycle length checked for alternating ping-pong loops. Set to `1` to disable
84
+ ping-pong cycle detection. Must be at least 1.
85
+ :param window_size: Maximum number of trailing tool-calling steps inspected per check. Must be at least
86
+ `stop_threshold`.
87
+ :param detect_consecutive_errors: Whether consecutive failing invocations of the same tool count as a loop.
88
+ :param add_final_message: Whether to append an assistant message explaining why the Agent stopped.
89
+ :raises ValueError: If any threshold or window parameter is outside its valid range.
90
+ """
91
+ if stop_threshold < 2:
92
+ raise ValueError(f"`stop_threshold` must be at least 2, got {stop_threshold}.")
93
+ if warn_threshold is not None:
94
+ if warn_threshold < 2:
95
+ raise ValueError(f"`warn_threshold` must be at least 2 or None, got {warn_threshold}.")
96
+ if warn_threshold >= stop_threshold:
97
+ raise ValueError(
98
+ f"`warn_threshold` ({warn_threshold}) must be less than `stop_threshold` ({stop_threshold})."
99
+ )
100
+ if max_cycle_length < 1:
101
+ raise ValueError(f"`max_cycle_length` must be at least 1, got {max_cycle_length}.")
102
+ if window_size < stop_threshold:
103
+ raise ValueError(
104
+ f"`window_size` ({window_size}) must be greater than or equal to `stop_threshold` ({stop_threshold})."
105
+ )
106
+
107
+ self.warn_threshold = warn_threshold
108
+ self.stop_threshold = stop_threshold
109
+ self.max_cycle_length = max_cycle_length
110
+ self.window_size = window_size
111
+ self.detect_consecutive_errors = detect_consecutive_errors
112
+ self.add_final_message = add_final_message
113
+
114
+ def run(self, state: State) -> None:
115
+ """
116
+ Inspect recent tool-calling steps and warn or stop the Agent if a loop is detected.
117
+
118
+ :param state: The Agent's live `State` containing `messages`.
119
+ """
120
+ messages = state.data.get("messages") or []
121
+ if not messages:
122
+ return
123
+
124
+ result, action = detect_tool_loop(
125
+ messages=messages,
126
+ warn_threshold=self.warn_threshold,
127
+ stop_threshold=self.stop_threshold,
128
+ max_cycle_length=self.max_cycle_length,
129
+ window_size=self.window_size,
130
+ detect_consecutive_errors=self.detect_consecutive_errors,
131
+ )
132
+ if result is None or action is None:
133
+ return
134
+
135
+ if action == "stop":
136
+ logger.warning("Agent stopped due to tool loop ({kind}): {detail}.", kind=result.kind, detail=result.detail)
137
+ state.set("stop_run", _EXIT_REASON_TOOL_LOOP)
138
+ if self.add_final_message:
139
+ state.set(
140
+ "messages", [ChatMessage.from_assistant(text=_FINAL_MESSAGE_TEMPLATE.format(detail=result.detail))]
141
+ )
142
+ return
143
+
144
+ key = _warning_key(result)
145
+ if messages[-1].meta.get(_LOOP_WARNING_META_KEY) == key:
146
+ return
147
+
148
+ logger.warning(
149
+ "Tool loop warning triggered ({kind}): {detail}; injecting reminder.",
150
+ kind=result.kind,
151
+ detail=result.detail,
152
+ )
153
+ text = _WARNING_TEMPLATE.format(detail=result.detail)
154
+ reminder = ChatMessage.from_user(
155
+ text=f"<system-reminder>\n{text}\n</system-reminder>",
156
+ meta={SYSTEM_REMINDER_META_KEY: True, _LOOP_WARNING_META_KEY: key},
157
+ )
158
+ state.set("messages", [reminder])
159
+
160
+ def to_dict(self) -> dict[str, Any]:
161
+ """
162
+ Serialize this hook to a dictionary.
163
+
164
+ :returns: Serialized representation of the hook.
165
+ """
166
+ return default_to_dict(
167
+ self,
168
+ warn_threshold=self.warn_threshold,
169
+ stop_threshold=self.stop_threshold,
170
+ max_cycle_length=self.max_cycle_length,
171
+ window_size=self.window_size,
172
+ detect_consecutive_errors=self.detect_consecutive_errors,
173
+ add_final_message=self.add_final_message,
174
+ )
175
+
176
+ @classmethod
177
+ def from_dict(cls, data: dict[str, Any]) -> "ToolLoopDetectionHook":
178
+ """
179
+ Create a hook from its serialized representation.
180
+
181
+ :param data: Serialized hook data.
182
+ :returns: The deserialized hook.
183
+ """
184
+ return default_from_dict(cls, data=data)
@@ -0,0 +1,438 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import asyncio
6
+ import logging
7
+ from typing import Annotated, Any
8
+ from unittest.mock import MagicMock
9
+
10
+ import pytest
11
+ from haystack.components.agents import Agent
12
+ from haystack.components.agents.state import State
13
+ from haystack.components.generators.chat import MockChatGenerator
14
+ from haystack.dataclasses import ChatMessage, ChatRole, ToolCall
15
+ from haystack.tools import tool
16
+
17
+ from haystack_integrations.hooks.loop_detection import LoopDetectionResult, ToolLoopDetectionHook
18
+ from haystack_integrations.hooks.loop_detection.detector import SYSTEM_REMINDER_META_KEY, detect_tool_loop
19
+
20
+
21
+ @tool
22
+ def search(query: Annotated[str, "search query"]) -> str:
23
+ """Search for information."""
24
+ return f"results for {query}"
25
+
26
+
27
+ @tool
28
+ def fetch(url: Annotated[str, "url to fetch"]) -> str:
29
+ """Fetch a webpage."""
30
+ return f"content of {url}"
31
+
32
+
33
+ @tool
34
+ def flaky(attempt: Annotated[int, "attempt number"]) -> str:
35
+ """Always raise an error to simulate a failing tool."""
36
+ raise RuntimeError(f"upstream failed on attempt {attempt}")
37
+
38
+
39
+ def _tool_step_messages(tool_calls: list[ToolCall], *, error_tools: set[str] | None = None) -> list[ChatMessage]:
40
+ error_tools = error_tools or set()
41
+ msgs = [ChatMessage.from_assistant(tool_calls=tool_calls)]
42
+ for tc in tool_calls:
43
+ is_error = tc.tool_name in error_tools
44
+ msgs.append(ChatMessage.from_tool(tool_result="boom" if is_error else "ok", origin=tc, error=is_error))
45
+ return msgs
46
+
47
+
48
+ def _state_with_messages(messages: list[ChatMessage]) -> State:
49
+ schema = {"messages": {"type": list[ChatMessage]}, "stop_run": {"type": str}}
50
+ return State(schema=schema, data={"messages": list(messages)})
51
+
52
+
53
+ class TestDetectToolLoop:
54
+ def test_exact_repeat_ignores_dict_key_and_parallel_call_order(self):
55
+ tc_a1 = ToolCall(tool_name="search", arguments={"a": 1, "b": 2}, id="1")
56
+ tc_b1 = ToolCall(tool_name="fetch", arguments={"url": "https://example.com"}, id="2")
57
+ tc_b2 = ToolCall(tool_name="fetch", arguments={"url": "https://example.com"}, id="3")
58
+ tc_a2 = ToolCall(tool_name="search", arguments={"b": 2, "a": 1}, id="4")
59
+
60
+ messages = [
61
+ ChatMessage.from_user("find info"),
62
+ *_tool_step_messages([tc_a1, tc_b1]),
63
+ *_tool_step_messages([tc_b2, tc_a2]),
64
+ ]
65
+ result, action = detect_tool_loop(
66
+ messages=messages,
67
+ warn_threshold=2,
68
+ stop_threshold=3,
69
+ max_cycle_length=3,
70
+ window_size=20,
71
+ detect_consecutive_errors=True,
72
+ )
73
+ assert action == "warn"
74
+ assert isinstance(result, LoopDetectionResult)
75
+ assert result.kind == "exact_repeat"
76
+ assert result.repetitions == 2
77
+ assert result.cycle_length == 1
78
+ assert result.tool_names == ("fetch", "search")
79
+
80
+ def test_ping_pong_cycle_detected_and_disableable(self):
81
+ a = ToolCall(tool_name="search", arguments={"query": "a"})
82
+ b = ToolCall(tool_name="fetch", arguments={"url": "https://a.test"})
83
+ messages = [
84
+ ChatMessage.from_user("loop"),
85
+ *_tool_step_messages([a]),
86
+ *_tool_step_messages([b]),
87
+ *_tool_step_messages([a]),
88
+ *_tool_step_messages([b]),
89
+ ]
90
+ result, action = detect_tool_loop(
91
+ messages=messages,
92
+ warn_threshold=2,
93
+ stop_threshold=3,
94
+ max_cycle_length=3,
95
+ window_size=20,
96
+ detect_consecutive_errors=True,
97
+ )
98
+ assert action == "warn"
99
+ assert result is not None
100
+ assert result.kind == "ping_pong"
101
+ assert result.cycle_length == 2
102
+ assert result.repetitions == 2
103
+ assert result.tool_names == ("search", "fetch")
104
+
105
+ no_result, no_action = detect_tool_loop(
106
+ messages=messages,
107
+ warn_threshold=2,
108
+ stop_threshold=3,
109
+ max_cycle_length=1,
110
+ window_size=20,
111
+ detect_consecutive_errors=True,
112
+ )
113
+ assert no_result is None
114
+ assert no_action is None
115
+
116
+ def test_consecutive_errors_detected_even_with_varying_arguments(self):
117
+ messages = [
118
+ ChatMessage.from_user("run flaky"),
119
+ *_tool_step_messages([ToolCall(tool_name="flaky", arguments={"attempt": 1})], error_tools={"flaky"}),
120
+ *_tool_step_messages([ToolCall(tool_name="flaky", arguments={"attempt": 2})], error_tools={"flaky"}),
121
+ *_tool_step_messages([ToolCall(tool_name="flaky", arguments={"attempt": 3})], error_tools={"flaky"}),
122
+ ]
123
+ result, action = detect_tool_loop(
124
+ messages=messages,
125
+ warn_threshold=2,
126
+ stop_threshold=3,
127
+ max_cycle_length=3,
128
+ window_size=20,
129
+ detect_consecutive_errors=True,
130
+ )
131
+ assert action == "stop"
132
+ assert result is not None
133
+ assert result.kind == "consecutive_error"
134
+ assert result.tool_names == ("flaky",)
135
+ assert result.repetitions == 3
136
+
137
+ disabled_result, disabled_action = detect_tool_loop(
138
+ messages=messages,
139
+ warn_threshold=2,
140
+ stop_threshold=3,
141
+ max_cycle_length=3,
142
+ window_size=20,
143
+ detect_consecutive_errors=False,
144
+ )
145
+ assert disabled_result is None
146
+ assert disabled_action is None
147
+
148
+ def test_new_user_turn_resets_window_but_system_reminder_does_not(self):
149
+ tc = ToolCall(tool_name="search", arguments={"query": "same"})
150
+ multi_turn_messages = [
151
+ ChatMessage.from_user("turn 1"),
152
+ *_tool_step_messages([tc]),
153
+ ChatMessage.from_assistant("turn 1 answer"),
154
+ ChatMessage.from_user("turn 2"),
155
+ *_tool_step_messages([tc]),
156
+ ]
157
+ result, action = detect_tool_loop(
158
+ messages=multi_turn_messages,
159
+ warn_threshold=2,
160
+ stop_threshold=3,
161
+ max_cycle_length=3,
162
+ window_size=20,
163
+ detect_consecutive_errors=True,
164
+ )
165
+ assert result is None
166
+ assert action is None
167
+
168
+ reminder = ChatMessage.from_user(
169
+ text="<system-reminder>\nkeep going\n</system-reminder>", meta={SYSTEM_REMINDER_META_KEY: True}
170
+ )
171
+ same_turn_with_reminder = [
172
+ ChatMessage.from_user("turn 1"),
173
+ *_tool_step_messages([tc]),
174
+ reminder,
175
+ *_tool_step_messages([tc]),
176
+ ]
177
+ result2, action2 = detect_tool_loop(
178
+ messages=same_turn_with_reminder,
179
+ warn_threshold=2,
180
+ stop_threshold=3,
181
+ max_cycle_length=3,
182
+ window_size=20,
183
+ detect_consecutive_errors=True,
184
+ )
185
+ assert action2 == "warn"
186
+ assert result2 is not None
187
+ assert result2.kind == "exact_repeat"
188
+ assert result2.repetitions == 2
189
+
190
+ def test_handles_non_json_serializable_tool_arguments(self):
191
+ tc1 = ToolCall(tool_name="search", arguments={"payload": {1, 2, 3}})
192
+ tc2 = ToolCall(tool_name="search", arguments={"payload": {1, 2, 3}})
193
+ messages = [ChatMessage.from_user("hi"), *_tool_step_messages([tc1]), *_tool_step_messages([tc2])]
194
+ result, action = detect_tool_loop(
195
+ messages=messages,
196
+ warn_threshold=2,
197
+ stop_threshold=3,
198
+ max_cycle_length=3,
199
+ window_size=20,
200
+ detect_consecutive_errors=True,
201
+ )
202
+ assert action == "warn"
203
+ assert result is not None
204
+ assert result.kind == "exact_repeat"
205
+
206
+
207
+ class TestToolLoopDetectionHook:
208
+ @pytest.mark.parametrize(
209
+ ("kwargs", "match"),
210
+ [
211
+ ({"stop_threshold": 1}, "`stop_threshold` must be at least 2"),
212
+ ({"warn_threshold": 1, "stop_threshold": 3}, "`warn_threshold` must be at least 2 or None"),
213
+ (
214
+ {"warn_threshold": 3, "stop_threshold": 3},
215
+ r"`warn_threshold` \(3\) must be less than `stop_threshold` \(3\)\.",
216
+ ),
217
+ ({"max_cycle_length": 0}, "`max_cycle_length` must be at least 1"),
218
+ ({"stop_threshold": 4, "window_size": 3}, r"`window_size` \(3\) must be greater than or equal"),
219
+ ],
220
+ )
221
+ def test_invalid_init_parameters_raise(self, kwargs, match):
222
+ with pytest.raises(ValueError, match=match):
223
+ ToolLoopDetectionHook(**kwargs)
224
+
225
+ def test_invalid_hook_point_rejected_by_agent(self):
226
+ with pytest.raises(ValueError, match="only supports: before_llm"):
227
+ Agent(chat_generator=MockChatGenerator(), tools=[search], hooks={"after_tool": [ToolLoopDetectionHook()]})
228
+
229
+ def test_to_dict_from_dict_roundtrip(self):
230
+ hook = ToolLoopDetectionHook(
231
+ warn_threshold=None,
232
+ stop_threshold=4,
233
+ max_cycle_length=2,
234
+ window_size=12,
235
+ detect_consecutive_errors=False,
236
+ add_final_message=True,
237
+ )
238
+ restored = ToolLoopDetectionHook.from_dict(hook.to_dict())
239
+ assert restored.warn_threshold is None
240
+ assert restored.stop_threshold == 4
241
+ assert restored.max_cycle_length == 2
242
+ assert restored.window_size == 12
243
+ assert restored.detect_consecutive_errors is False
244
+ assert restored.add_final_message is True
245
+
246
+ def test_agent_serialization_roundtrip_with_hook(self, monkeypatch):
247
+ # Haystack trusts the hook namespace by default. The local search tool lives in this test module.
248
+ monkeypatch.setenv("HAYSTACK_DESERIALIZATION_ALLOWLIST", __name__)
249
+ agent = Agent(
250
+ chat_generator=MockChatGenerator(),
251
+ tools=[search],
252
+ hooks={"before_llm": [ToolLoopDetectionHook(warn_threshold=2, stop_threshold=4, add_final_message=True)]},
253
+ )
254
+ restored = Agent.from_dict(agent.to_dict())
255
+ assert len(restored.hooks["before_llm"]) == 1
256
+ restored_hook = restored.hooks["before_llm"][0]
257
+ assert isinstance(restored_hook, ToolLoopDetectionHook)
258
+ assert restored_hook.warn_threshold == 2
259
+ assert restored_hook.stop_threshold == 4
260
+ assert restored_hook.add_final_message is True
261
+
262
+ def test_warn_is_idempotent_on_same_state(self):
263
+ tc = ToolCall(tool_name="search", arguments={"query": "dup"})
264
+ state = _state_with_messages(
265
+ [ChatMessage.from_user("hi"), *_tool_step_messages([tc]), *_tool_step_messages([tc])]
266
+ )
267
+ hook = ToolLoopDetectionHook(warn_threshold=2, stop_threshold=3)
268
+
269
+ hook.run(state)
270
+ count_after_first = len(state.data["messages"])
271
+ assert state.data["messages"][-1].meta[SYSTEM_REMINDER_META_KEY] is True
272
+ assert "tool_loop_warning" in state.data["messages"][-1].meta
273
+
274
+ hook.run(state)
275
+ assert len(state.data["messages"]) == count_after_first
276
+
277
+ def test_warn_threshold_none_skips_reminder_and_stops_directly(self, caplog):
278
+ tc = ToolCall(tool_name="search", arguments={"query": "x"})
279
+ hook = ToolLoopDetectionHook(warn_threshold=None, stop_threshold=3, add_final_message=True)
280
+
281
+ state_2 = _state_with_messages(
282
+ [ChatMessage.from_user("hi"), *_tool_step_messages([tc]), *_tool_step_messages([tc])]
283
+ )
284
+ hook.run(state_2)
285
+ assert state_2.data.get("stop_run") is None
286
+ assert not any(SYSTEM_REMINDER_META_KEY in m.meta for m in state_2.data["messages"])
287
+
288
+ state_3 = _state_with_messages(
289
+ [
290
+ ChatMessage.from_user("hi"),
291
+ *_tool_step_messages([tc]),
292
+ *_tool_step_messages([tc]),
293
+ *_tool_step_messages([tc]),
294
+ ]
295
+ )
296
+ with caplog.at_level(logging.WARNING):
297
+ hook.run(state_3)
298
+ assert state_3.data["stop_run"] == "tool_loop_detected"
299
+ assert state_3.data["messages"][-1].is_from(ChatRole.ASSISTANT)
300
+ assert "tool-calling loop was detected" in (state_3.data["messages"][-1].text or "")
301
+ assert "exact_repeat" in caplog.text
302
+
303
+ def test_agent_warns_then_stops_on_exact_repeat(self, monkeypatch):
304
+ agent = Agent(
305
+ chat_generator=MockChatGenerator(),
306
+ tools=[search],
307
+ max_agent_steps=10,
308
+ hooks={"before_llm": [ToolLoopDetectionHook(warn_threshold=2, stop_threshold=3)]},
309
+ )
310
+ agent.warm_up()
311
+ seen_last_messages: list[ChatMessage] = []
312
+
313
+ def fake_run(messages: list[ChatMessage], **kwargs: Any) -> dict[str, Any]:
314
+ seen_last_messages.append(messages[-1])
315
+ return {"replies": [ChatMessage.from_assistant(tool_calls=[ToolCall("search", {"query": "loop"})])]}
316
+
317
+ mock_run = MagicMock(side_effect=fake_run)
318
+ monkeypatch.setattr(agent.chat_generator, "run", mock_run)
319
+ result = agent.run(messages=[ChatMessage.from_user("start")])
320
+
321
+ assert result["exit_reason"] == "tool_loop_detected"
322
+ assert result["step_count"] == 3
323
+ assert mock_run.call_count == 3
324
+ assert seen_last_messages[2].is_from(ChatRole.USER)
325
+ assert seen_last_messages[2].meta.get(SYSTEM_REMINDER_META_KEY) is True
326
+ assert "Loop detection warning:" in (seen_last_messages[2].text or "")
327
+
328
+ def test_agent_recovers_after_loop_warning(self, monkeypatch):
329
+ agent = Agent(
330
+ chat_generator=MockChatGenerator(),
331
+ tools=[search],
332
+ max_agent_steps=10,
333
+ hooks={"before_llm": [ToolLoopDetectionHook(warn_threshold=2, stop_threshold=3)]},
334
+ )
335
+ agent.warm_up()
336
+
337
+ def fake_run(messages: list[ChatMessage], **kwargs: Any) -> dict[str, Any]:
338
+ if messages[-1].meta.get(SYSTEM_REMINDER_META_KEY):
339
+ return {"replies": [ChatMessage.from_assistant("Recovered with final answer.")]}
340
+ return {"replies": [ChatMessage.from_assistant(tool_calls=[ToolCall("search", {"query": "loop"})])]}
341
+
342
+ monkeypatch.setattr(agent.chat_generator, "run", MagicMock(side_effect=fake_run))
343
+ result = agent.run(messages=[ChatMessage.from_user("start")])
344
+
345
+ assert result["exit_reason"] == "text"
346
+ assert result["last_message"].text == "Recovered with final answer."
347
+ assert result["step_count"] == 3
348
+
349
+ def test_agent_stops_on_ping_pong_cycle(self, monkeypatch):
350
+ agent = Agent(
351
+ chat_generator=MockChatGenerator(),
352
+ tools=[search, fetch],
353
+ max_agent_steps=12,
354
+ hooks={"before_llm": [ToolLoopDetectionHook(warn_threshold=2, stop_threshold=3, max_cycle_length=2)]},
355
+ )
356
+ agent.warm_up()
357
+ call_idx = 0
358
+
359
+ def fake_run(messages: list[ChatMessage], **kwargs: Any) -> dict[str, Any]:
360
+ nonlocal call_idx
361
+ tc = (
362
+ ToolCall("search", {"query": "ping"})
363
+ if call_idx % 2 == 0
364
+ else ToolCall("fetch", {"url": "https://pong.test"})
365
+ )
366
+ call_idx += 1
367
+ return {"replies": [ChatMessage.from_assistant(tool_calls=[tc])]}
368
+
369
+ monkeypatch.setattr(agent.chat_generator, "run", MagicMock(side_effect=fake_run))
370
+ result = agent.run(messages=[ChatMessage.from_user("start")])
371
+
372
+ assert result["exit_reason"] == "tool_loop_detected"
373
+ assert result["step_count"] == 6
374
+
375
+ def test_agent_stops_on_consecutive_tool_errors(self, monkeypatch):
376
+ agent = Agent(
377
+ chat_generator=MockChatGenerator(),
378
+ tools=[flaky],
379
+ max_agent_steps=10,
380
+ hooks={"before_llm": [ToolLoopDetectionHook(warn_threshold=2, stop_threshold=3)]},
381
+ )
382
+ agent.warm_up()
383
+ attempt = 0
384
+
385
+ def fake_run(messages: list[ChatMessage], **kwargs: Any) -> dict[str, Any]:
386
+ nonlocal attempt
387
+ attempt += 1
388
+ return {"replies": [ChatMessage.from_assistant(tool_calls=[ToolCall("flaky", {"attempt": attempt})])]}
389
+
390
+ monkeypatch.setattr(agent.chat_generator, "run", MagicMock(side_effect=fake_run))
391
+ result = agent.run(messages=[ChatMessage.from_user("run flaky")])
392
+
393
+ assert result["exit_reason"] == "tool_loop_detected"
394
+ assert result["step_count"] == 3
395
+
396
+ @pytest.mark.asyncio
397
+ async def test_shared_hook_is_isolated_across_concurrent_async_runs(self, monkeypatch):
398
+ shared_hook = ToolLoopDetectionHook(warn_threshold=2, stop_threshold=3)
399
+ agent = Agent(
400
+ chat_generator=MockChatGenerator(), tools=[search], max_agent_steps=10, hooks={"before_llm": [shared_hook]}
401
+ )
402
+ await agent.warm_up_async()
403
+
404
+ async def fake_run_async(messages: list[ChatMessage], **kwargs: Any) -> dict[str, Any]:
405
+ await asyncio.sleep(0)
406
+ prompt = messages[0].text or ""
407
+ if prompt == "looping":
408
+ return {"replies": [ChatMessage.from_assistant(tool_calls=[ToolCall("search", {"query": "same"})])]}
409
+ if len(messages) == 1:
410
+ return {"replies": [ChatMessage.from_assistant(tool_calls=[ToolCall("search", {"query": "once"})])]}
411
+ return {"replies": [ChatMessage.from_assistant("healthy done")]}
412
+
413
+ monkeypatch.setattr(agent.chat_generator, "run_async", fake_run_async)
414
+ loop_res, healthy_res = await asyncio.gather(
415
+ agent.run_async(messages=[ChatMessage.from_user("looping")]),
416
+ agent.run_async(messages=[ChatMessage.from_user("healthy")]),
417
+ )
418
+
419
+ assert loop_res["exit_reason"] == "tool_loop_detected"
420
+ assert loop_res["step_count"] == 3
421
+ assert healthy_res["exit_reason"] == "text"
422
+ assert healthy_res["last_message"].text == "healthy done"
423
+
424
+ def test_agent_without_hook_behavior_unchanged(self, monkeypatch):
425
+ agent = Agent(chat_generator=MockChatGenerator(), tools=[search], max_agent_steps=4)
426
+ agent.warm_up()
427
+ monkeypatch.setattr(
428
+ agent.chat_generator,
429
+ "run",
430
+ MagicMock(
431
+ return_value={
432
+ "replies": [ChatMessage.from_assistant(tool_calls=[ToolCall("search", {"query": "same"})])]
433
+ }
434
+ ),
435
+ )
436
+ result = agent.run(messages=[ChatMessage.from_user("start")])
437
+ assert result["exit_reason"] == "max_agent_steps"
438
+ assert result["step_count"] == 4