Enforce a Max-Steps Agent Loop Guard

Basics
BasicsState MachinesGuardrailsOpenAIAnthropicGoogle

Problem

Given a list of planned agent actions and an integer max_steps, implement run_bounded_loop(actions, max_steps) that steps through at most max_steps actions. If it encounters 'finish' within max_steps, return ("FINISHED", step_number) (1-indexed); otherwise return ("MAX_STEPS", steps_executed).

Why It Matters: Every production agent loop requires a hard max_steps ceiling so a confused LLM cannot loop indefinitely and drain API credits.

Function Signature

def run_bounded_loop(actions: list[str], max_steps: int) -> tuple[str, int]:
    """Run actions up to max_steps; stop early on 'finish'."""

Sample Input & Output

Example 1: Finishes Within Step Budget

Input:

actions = ["search", "read", "finish", "extra"], max_steps = 5

Expected Output:

("FINISHED", 3)

Explanation: 'finish' appears at 1-indexed step 3, halting immediately before 'extra'.

Example 2: Hits Max Steps Ceiling

Input:

actions = ["search", "retry", "retry", "finish"], max_steps = 3

Expected Output:

("MAX_STEPS", 3)

Explanation: 'finish' is at step 4, beyond max_steps = 3, so the guard stops at 3 steps.

Example 3: Action List Shorter Than max_steps Without Finish

Input:

actions = ["search", "read"], max_steps = 5

Expected Output:

("MAX_STEPS", 2)

Explanation: Only 2 actions existed and none was 'finish', so steps_executed = 2.

Constraints & Edge Cases

  • Return (status, steps_taken) where status is 'FINISHED' or 'MAX_STEPS'.
  • Step numbers are 1-indexed.
  • If max_steps == 0 or actions == [], returns ('MAX_STEPS', 0).

Constraints & Evaluation Criteria

  • Return `(status, steps_taken)` where `status` is `'FINISHED'` or `'MAX_STEPS'`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
['search','finish'], max=5
Expected Output / Criteria
('FINISHED', 2)