{"record":{"id":"5c15d48a604092cb","repo":"huggingface/smolagents","slug":"maximum-number-of-max-while-iterations-iteration","errorCode":null,"errorMessage":"Maximum number of {MAX_WHILE_ITERATIONS} iterations in While loop exceeded","messagePattern":"Maximum number of (.+?) iterations in While loop exceeded","errorType":"error_code","errorClass":"InterpreterError","httpStatus":null,"severity":"error","filePath":"src/smolagents/local_python_executor.py","lineNumber":458,"sourceCode":"def evaluate_while(\n    while_loop: ast.While,\n    state: dict[str, Any],\n    static_tools: dict[str, Callable],\n    custom_tools: dict[str, Callable],\n    authorized_imports: list[str],\n) -> None:\n    iterations = 0\n    while evaluate_ast(while_loop.test, state, static_tools, custom_tools, authorized_imports):\n        for node in while_loop.body:\n            try:\n                evaluate_ast(node, state, static_tools, custom_tools, authorized_imports)\n            except BreakException:\n                return None\n            except ContinueException:\n                break\n        iterations += 1\n        if iterations > MAX_WHILE_ITERATIONS:\n            raise InterpreterError(f\"Maximum number of {MAX_WHILE_ITERATIONS} iterations in While loop exceeded\")\n    return None\n\n\ndef create_function(\n    func_def: ast.FunctionDef,\n    state: dict[str, Any],\n    static_tools: dict[str, Callable],\n    custom_tools: dict[str, Callable],\n    authorized_imports: list[str],\n) -> Callable:\n    source_code = ast.unparse(func_def)\n\n    def new_func(*args: Any, **kwargs: Any) -> Any:\n        func_state = state.copy()\n        arg_names = [arg.arg for arg in func_def.args.args]\n        default_values = [\n            evaluate_ast(d, state, static_tools, custom_tools, authorized_imports) for d in func_def.args.defaults\n        ]","sourceCodeStart":440,"sourceCodeEnd":476,"githubUrl":"https://github.com/huggingface/smolagents/blob/30bb1161095dbae2271e6bc3cc4c219cc3897a57/src/smolagents/local_python_executor.py#L440-L476","documentation":"The executor caps while loops at MAX_WHILE_ITERATIONS (100_000) iterations to prevent runaway generated code; exceeding it raises InterpreterError even though the condition may still be true. This is a CPU-bound guard independent of the wall-clock timeout.","triggerScenarios":"A while loop in executed code runs more than MAX_WHILE_ITERATIONS times: `while True:` with no break, `while x != target:` that never converges, or a loop whose counter update is wrong (e.g. decrementing a variable it never reads).","commonSituations":"LLM writes `while True` intending a few iterations; loop variable shadowed or updated inside an inner function so the condition never changes; searching without a bound; off-by-one making the exit condition unreachable.","solutions":["Add an explicit iteration cap and break in the loop: `for _ in range(10_000): ... ` or `i += 1; if i > N: break`","Fix the loop condition/counter so it actually converges (verify the mutated variable is the one tested)","Convert the while to a bounded for-range loop, which is easier for the model to get right"],"exampleFix":"# before\ncode = \"i = 0\\nwhile True:\\n    i += 1\\nfinal_answer(i)\"\n\n# after\ncode = \"i = 0\\nwhile i < 100:\\n    i += 1\\nfinal_answer(i)\"","handlingStrategy":"validation","validationCode":"import ast\nMAX = 100_000\nfor node in ast.walk(ast.parse(code)):\n    if isinstance(node, ast.While):\n        has_break = any(isinstance(x, ast.Break) for x in ast.walk(node))\n        has_cap = 'max_iter' in code or 'range(' in ast.dump(node)\n        if not (has_break or has_cap):\n            raise ValueError('unbounded while loop detected; add a counter/break')","typeGuard":null,"tryCatchPattern":"from smolagents.local_python_executor import InterpreterError\ntry:\n    evaluate_python(code)\nexcept InterpreterError as e:\n    if 'While loop exceeded' in str(e):\n        code = code.replace('while True', 'for _ in range(10000)')\n        evaluate_python(code)","preventionTips":["Prefer for-range loops over while in generated code","Always include an explicit iteration cap and break","Check that the loop counter is actually the variable in the condition"],"tags":["smolagents","while-loop","infinite-loop","iteration-limit","sandbox"],"backgroundTag":"infinite-loop-guard","analyzedSha":"30bb1161095dbae2271e6bc3cc4c219cc3897a57","analyzedAt":"2026-08-28T18:52:54.169Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}