Implement Termination Conditions for Agent Loops

Easy
Agents

Agent Termination Conditions

Without proper termination, agents run infinitely, waste tokens, and incur costs.

Task

Implement:

  1. TerminationCondition: A composable set of termination predicates.
  2. BoundedAgentLoop: Enforces max steps and cost limits.

Constraints

  • Terminate if: max steps exceeded, cost budget exceeded, task complete flag set, or error state.
  • State is a dict with keys: steps, cost, done, error.
  • Log reason for termination.

Examples

Example 1:
Input: tc = TerminationCondition() tc.add_condition(lambda s: s['steps'] >= 5) tc.should_terminate({'steps': 5, 'cost': 0})
Output: True
Explanation: Step limit reached.

Starter Code

from typing import List, Callable

class TerminationCondition:
    def __init__(self):
        self.conditions: List[Callable[[dict], bool]] = []

    def add_condition(self, fn: Callable[[dict], bool]) -> None:
        # TODO: Register a termination condition
        pass

    def should_terminate(self, state: dict) -> bool:
        # TODO: Return True if ANY condition is met
        pass

class BoundedAgentLoop:
    def __init__(self, max_steps: int, max_cost: float):
        # TODO: Initialize with bounds
        pass

    def step(self, action_fn: Callable, state: dict) -> dict:
        # TODO: Execute one step, update state, check termination
        pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews