Neural Mastery
← Practice
Detect Cyclic Tool Call Chainhard

Detect Cyclic Tool Call Chain

hard Agents in Production 15 min

NumPy allowed · plain Python earns 10 bonus points

Implement cyclic tool-call chain detection, a real safety check preventing an agent from getting stuck in an infinite tool-calling loop (tool A triggers tool B triggers tool A again).

Task

Implement has_cyclic_tool_chain(call_chain). call_chain is the ORDERED sequence of tool names called so far in the current agent turn. Return True if any CONSECUTIVE, CONTIGUOUS subsequence of length >= 2 repeats immediately after itself (e.g. [A,B,A,B] has [A,B] repeating -- a real detected loop). Check repeat-unit lengths from 1 up to len(call_chain)//2.

Function Signature

has_cyclic_tool_chain(call_chain: list[str]) -> bool

Examples

Example 1: simple two-step loop
Input: call_chain = ['A', 'B', 'A', 'B']
Output: True
Example 2: no loop, all distinct
Input: call_chain = ['A', 'B', 'C', 'D']
Output: False
Example 3: immediate single-tool repeat
Input: call_chain = ['A', 'A']
Output: True

Constraints

  • call_chain is a list of tool names
Python3Saved ✓
def has_cyclic_tool_chain(call_chain):
# Your implementation here
pass

Case 1: simple two-step loop
Input: call_chain = ['A', 'B', 'A', 'B']
Expected: True
Case 2: no loop, all distinct
Input: call_chain = ['A', 'B', 'C', 'D']
Expected: False
Case 3: immediate single-tool repeat
Input: call_chain = ['A', 'A']
Expected: True