Implement a basic agent execution loop that:
- Starts with initial_input as state
- Calls step_func(state) to get new state
- Checks should_stop(new_state) for termination
- Stops if should_stop returns True OR max_iterations reached
- Returns final results
Safety Requirements:
- Must respect max_iterations (hard stop)
- Count iterations correctly
- 'terminated' is True if stopped by should_stop, False if by max_iterations
- Handle case where should_stop is True immediately
Examples
Example 1:
Input:
run_agent_loop(0, lambda x: x+1, lambda x: x>=5, 10)Output:
{'final_state': 5, 'iterations': 5, 'terminated': True}Explanation: Increments from 0, stops at 5 (should_stop true), 5 iterations
Example 2:
Input:
run_agent_loop(0, lambda x: x+1, lambda x: False, 3)Output:
{'final_state': 3, 'iterations': 3, 'terminated': False}Explanation: Never meets stop condition, hits max_iterations, terminated=False
Starter Code
def run_agent_loop(initial_input, step_func, should_stop, max_iterations=10):
"""
Execute a basic agent loop with termination conditions.
Args:
initial_input: Starting input for the agent
step_func: Function(state) -> new_state
should_stop: Function(state) -> bool (termination condition)
max_iterations: Safety limit to prevent infinite loops
Returns:
dict with 'final_state', 'iterations', 'terminated' (bool)
"""
# Your implementation here
passPython3
ReadyLines: 1Characters: 0
Ready