Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce counter class #891

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/smolagents/local_python_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,21 @@ def custom_print(*args):
]


class OperationsCounter:
"""
Simple counter to limit the number of operations in a single evaluation.
"""

def __init__(self):
self.count = 0

def increment(self):
self.count += 1

def __call__(self):
return self.count


class PrintContainer:
def __init__(self):
self.value = ""
Expand Down Expand Up @@ -1263,11 +1278,11 @@ def evaluate_ast(
The list of modules that can be imported by the code. By default, only a few safe modules are allowed.
If it contains "*", it will authorize any import. Use this at your own risk!
"""
if state.setdefault("_operations_count", 0) >= MAX_OPERATIONS:
if state.setdefault("_operations_count", OperationsCounter())() >= MAX_OPERATIONS:
raise InterpreterError(
f"Reached the max number of operations of {MAX_OPERATIONS}. Maybe there is an infinite loop somewhere in the code, or you're just asking too many calculations."
)
state["_operations_count"] += 1
state["_operations_count"].increment()
common_params = (state, static_tools, custom_tools, authorized_imports)
if isinstance(expression, ast.Assign):
# Assignment -> we evaluate the assignment which should update the state
Expand Down Expand Up @@ -1437,7 +1452,7 @@ def evaluate_python_code(
custom_tools = custom_tools if custom_tools is not None else {}
result = None
state["_print_outputs"] = PrintContainer()
state["_operations_count"] = 0
state["_operations_count"] = OperationsCounter()

if "final_answer" in static_tools:
previous_final_answer = static_tools["final_answer"]
Expand Down