-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathlocal_python_executor.py
More file actions
1734 lines (1583 loc) · 58.3 KB
/
local_python_executor.py
File metadata and controls
1734 lines (1583 loc) · 58.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding=utf-8
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# from smolagents.local_python_executor with modifications to remove
# final_answer since we want limit the ability of the agent to find
# the final_answer on its own. The agent must call one of the tools
# with the right arguments and state to find the answer.
# This also adds tracing to the interpreter for tool analysis.
import ast
import builtins
import difflib
import inspect
import logging
import math
import re
from collections.abc import Mapping
from importlib import import_module
from types import ModuleType
from typing import Any, Callable, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
# from smolagents/src/smolagents/utils.py
MAX_LENGTH_TRUNCATE_CONTENT = 20000
def truncate_content(
content: str, max_length: int = MAX_LENGTH_TRUNCATE_CONTENT
) -> str:
if len(content) <= max_length:
return content
else:
return (
content[: max_length // 2]
+ f"\n..._This content has been truncated to stay below {max_length} characters_...\n"
+ content[-max_length // 2 :]
)
# from smolagents/src/smolagents/utils.py
BASE_BUILTIN_MODULES = [
"collections",
"datetime",
"itertools",
"math",
"queue",
"random",
"re",
"stat",
"statistics",
"time",
"unicodedata",
]
class InterpreterError(ValueError):
"""
An error raised when the interpreter cannot evaluate a Python expression, due to syntax error or unsupported
operations.
"""
pass
ERRORS = {
name: getattr(builtins, name)
for name in dir(builtins)
if isinstance(getattr(builtins, name), type)
and issubclass(getattr(builtins, name), BaseException)
}
DEFAULT_MAX_LEN_OUTPUT = 50000
MAX_OPERATIONS = 10000000
MAX_WHILE_ITERATIONS = 1000000
def custom_print(*args):
return None
BASE_PYTHON_TOOLS = {
"print": custom_print,
"isinstance": isinstance,
"range": range,
"float": float,
"int": int,
"bool": bool,
"str": str,
"set": set,
"list": list,
"dict": dict,
"tuple": tuple,
"round": round,
"ceil": math.ceil,
"floor": math.floor,
"log": math.log,
"exp": math.exp,
"sin": math.sin,
"cos": math.cos,
"tan": math.tan,
"asin": math.asin,
"acos": math.acos,
"atan": math.atan,
"atan2": math.atan2,
"degrees": math.degrees,
"radians": math.radians,
"pow": pow,
"sqrt": math.sqrt,
"len": len,
"sum": sum,
"max": max,
"min": min,
"abs": abs,
"enumerate": enumerate,
"zip": zip,
"reversed": reversed,
"sorted": sorted,
"all": all,
"any": any,
"map": map,
"filter": filter,
"ord": ord,
"chr": chr,
"next": next,
"iter": iter,
"divmod": divmod,
"callable": callable,
"getattr": getattr,
"hasattr": hasattr,
"setattr": setattr,
"issubclass": issubclass,
"type": type,
"complex": complex,
}
class PrintContainer:
def __init__(self):
self.value = ""
def append(self, text):
self.value += text
return self
def __iadd__(self, other):
"""Implements the += operator"""
self.value += str(other)
return self
def __str__(self):
"""String representation"""
return self.value
def __repr__(self):
"""Representation for debugging"""
return f"PrintContainer({self.value})"
def __len__(self):
"""Implements len() function support"""
return len(self.value)
class BreakException(Exception):
pass
class ContinueException(Exception):
pass
class ReturnException(Exception):
def __init__(self, value):
self.value = value
def get_iterable(obj):
if isinstance(obj, list):
return obj
elif hasattr(obj, "__iter__"):
return list(obj)
else:
raise InterpreterError("Object is not iterable")
def fix_final_answer_code(code: str) -> str:
"""
Sometimes an LLM can try to assign a variable to final_answer, which would break the final_answer() tool.
This function fixes this behaviour by replacing variable assignments to final_answer with final_answer_variable,
while preserving function calls to final_answer().
"""
# First, find if there's a direct assignment to final_answer
# Use word boundary and negative lookbehind to ensure it's not an object attribute
assignment_pattern = r"(?<!\.)(?<!\w)\bfinal_answer\s*="
if "final_answer(" not in code or not re.search(assignment_pattern, code):
# If final_answer tool is not called in this blob, then doing the replacement is hazardous because it could false the model's memory for next steps.
# Let's not modify the code and leave the subsequent assignment error happen.
return code
# Pattern for replacing variable assignments
# Looks for 'final_answer' followed by '=' with optional whitespace
# Negative lookbehind ensures we don't match object attributes
assignment_regex = r"(?<!\.)(?<!\w)(\bfinal_answer)(\s*=)"
code = re.sub(assignment_regex, r"final_answer_variable\2", code)
# Pattern for replacing variable usage but not function calls
# Negative lookahead (?!\s*\() ensures we don't match function calls
# Negative lookbehind (?<!\.|\w) ensures we don't match object methods or other variables
variable_regex = r"(?<!\.)(?<!\w)(\bfinal_answer\b)(?!\s*\()"
code = re.sub(variable_regex, "final_answer_variable", code)
return code
def evaluate_unaryop(
expression: ast.UnaryOp,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Any:
operand = evaluate_ast(
expression.operand, state, static_tools, custom_tools, authorized_imports
)
if isinstance(expression.op, ast.USub):
return -operand
elif isinstance(expression.op, ast.UAdd):
return operand
elif isinstance(expression.op, ast.Not):
return not operand
elif isinstance(expression.op, ast.Invert):
return ~operand
else:
raise InterpreterError(
f"Unary operation {expression.op.__class__.__name__} is not supported."
)
def evaluate_lambda(
lambda_expression: ast.Lambda,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Callable:
args = [arg.arg for arg in lambda_expression.args.args]
def lambda_func(*values: Any) -> Any:
new_state = state.copy()
for arg, value in zip(args, values):
new_state[arg] = value
return evaluate_ast(
lambda_expression.body,
new_state,
static_tools,
custom_tools,
authorized_imports,
)
return lambda_func
def evaluate_while(
while_loop: ast.While,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> None:
iterations = 0
while evaluate_ast(
while_loop.test, state, static_tools, custom_tools, authorized_imports
):
for node in while_loop.body:
try:
evaluate_ast(
node, state, static_tools, custom_tools, authorized_imports
)
except BreakException:
return None
except ContinueException:
break
iterations += 1
if iterations > MAX_WHILE_ITERATIONS:
raise InterpreterError(
f"Maximum number of {MAX_WHILE_ITERATIONS} iterations in While loop exceeded"
)
return None
def create_function(
func_def: ast.FunctionDef,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Callable:
def new_func(*args: Any, **kwargs: Any) -> Any:
func_state = state.copy()
arg_names = [arg.arg for arg in func_def.args.args]
default_values = [
evaluate_ast(d, state, static_tools, custom_tools, authorized_imports)
for d in func_def.args.defaults
]
# Apply default values
defaults = dict(zip(arg_names[-len(default_values) :], default_values))
# Set positional arguments
for name, value in zip(arg_names, args):
func_state[name] = value
# Set keyword arguments
for name, value in kwargs.items():
func_state[name] = value
# Handle variable arguments
if func_def.args.vararg:
vararg_name = func_def.args.vararg.arg
func_state[vararg_name] = args
if func_def.args.kwarg:
kwarg_name = func_def.args.kwarg.arg
func_state[kwarg_name] = kwargs
# Set default values for arguments that were not provided
for name, value in defaults.items():
if name not in func_state:
func_state[name] = value
# Update function state with self and __class__
if func_def.args.args and func_def.args.args[0].arg == "self":
if args:
func_state["self"] = args[0]
func_state["__class__"] = args[0].__class__
result = None
try:
for stmt in func_def.body:
result = evaluate_ast(
stmt, func_state, static_tools, custom_tools, authorized_imports
)
except ReturnException as e:
result = e.value
if func_def.name == "__init__":
return None
return result
return new_func
def evaluate_function_def(
func_def: ast.FunctionDef,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Callable:
custom_tools[func_def.name] = create_function(
func_def, state, static_tools, custom_tools, authorized_imports
)
return custom_tools[func_def.name]
def evaluate_class_def(
class_def: ast.ClassDef,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> type:
class_name = class_def.name
bases = [
evaluate_ast(base, state, static_tools, custom_tools, authorized_imports)
for base in class_def.bases
]
class_dict = {}
for stmt in class_def.body:
if isinstance(stmt, ast.FunctionDef):
class_dict[stmt.name] = evaluate_function_def(
stmt, state, static_tools, custom_tools, authorized_imports
)
elif isinstance(stmt, ast.Assign):
for target in stmt.targets:
if isinstance(target, ast.Name):
class_dict[target.id] = evaluate_ast(
stmt.value,
state,
static_tools,
custom_tools,
authorized_imports,
)
elif isinstance(target, ast.Attribute):
class_dict[target.attr] = evaluate_ast(
stmt.value,
state,
static_tools,
custom_tools,
authorized_imports,
)
else:
raise InterpreterError(
f"Unsupported statement in class body: {stmt.__class__.__name__}"
)
new_class = type(class_name, tuple(bases), class_dict)
state[class_name] = new_class
return new_class
def evaluate_augassign(
expression: ast.AugAssign,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Any:
def get_current_value(target: ast.AST) -> Any:
if isinstance(target, ast.Name):
return state.get(target.id, 0)
elif isinstance(target, ast.Subscript):
obj = evaluate_ast(
target.value, state, static_tools, custom_tools, authorized_imports
)
key = evaluate_ast(
target.slice, state, static_tools, custom_tools, authorized_imports
)
return obj[key]
elif isinstance(target, ast.Attribute):
obj = evaluate_ast(
target.value, state, static_tools, custom_tools, authorized_imports
)
return getattr(obj, target.attr)
elif isinstance(target, ast.Tuple):
return tuple(get_current_value(elt) for elt in target.elts)
elif isinstance(target, ast.List):
return [get_current_value(elt) for elt in target.elts]
else:
raise InterpreterError(
"AugAssign not supported for {type(target)} targets."
)
current_value = get_current_value(expression.target)
value_to_add = evaluate_ast(
expression.value, state, static_tools, custom_tools, authorized_imports
)
if isinstance(expression.op, ast.Add):
if isinstance(current_value, list):
if not isinstance(value_to_add, list):
raise InterpreterError(
f"Cannot add non-list value {value_to_add} to a list."
)
current_value += value_to_add
else:
current_value += value_to_add
elif isinstance(expression.op, ast.Sub):
current_value -= value_to_add
elif isinstance(expression.op, ast.Mult):
current_value *= value_to_add
elif isinstance(expression.op, ast.Div):
current_value /= value_to_add
elif isinstance(expression.op, ast.Mod):
current_value %= value_to_add
elif isinstance(expression.op, ast.Pow):
current_value **= value_to_add
elif isinstance(expression.op, ast.FloorDiv):
current_value //= value_to_add
elif isinstance(expression.op, ast.BitAnd):
current_value &= value_to_add
elif isinstance(expression.op, ast.BitOr):
current_value |= value_to_add
elif isinstance(expression.op, ast.BitXor):
current_value ^= value_to_add
elif isinstance(expression.op, ast.LShift):
current_value <<= value_to_add
elif isinstance(expression.op, ast.RShift):
current_value >>= value_to_add
else:
raise InterpreterError(
f"Operation {type(expression.op).__name__} is not supported."
)
# Update the state: current_value has been updated in-place
set_value(
expression.target,
current_value,
state,
static_tools,
custom_tools,
authorized_imports,
)
return current_value
def evaluate_boolop(
node: ast.BoolOp,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> bool:
if isinstance(node.op, ast.And):
for value in node.values:
if not evaluate_ast(
value, state, static_tools, custom_tools, authorized_imports
):
return False
return True
elif isinstance(node.op, ast.Or):
for value in node.values:
if evaluate_ast(
value, state, static_tools, custom_tools, authorized_imports
):
return True
return False
def evaluate_binop(
binop: ast.BinOp,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Any:
# Recursively evaluate the left and right operands
left_val = evaluate_ast(
binop.left, state, static_tools, custom_tools, authorized_imports
)
right_val = evaluate_ast(
binop.right, state, static_tools, custom_tools, authorized_imports
)
# Determine the operation based on the type of the operator in the BinOp
if isinstance(binop.op, ast.Add):
return left_val + right_val
elif isinstance(binop.op, ast.Sub):
return left_val - right_val
elif isinstance(binop.op, ast.Mult):
return left_val * right_val
elif isinstance(binop.op, ast.Div):
return left_val / right_val
elif isinstance(binop.op, ast.Mod):
return left_val % right_val
elif isinstance(binop.op, ast.Pow):
return left_val**right_val
elif isinstance(binop.op, ast.FloorDiv):
return left_val // right_val
elif isinstance(binop.op, ast.BitAnd):
return left_val & right_val
elif isinstance(binop.op, ast.BitOr):
return left_val | right_val
elif isinstance(binop.op, ast.BitXor):
return left_val ^ right_val
elif isinstance(binop.op, ast.LShift):
return left_val << right_val
elif isinstance(binop.op, ast.RShift):
return left_val >> right_val
else:
raise NotImplementedError(
f"Binary operation {type(binop.op).__name__} is not implemented."
)
def evaluate_assign(
assign: ast.Assign,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Any:
result = evaluate_ast(
assign.value, state, static_tools, custom_tools, authorized_imports
)
if len(assign.targets) == 1:
target = assign.targets[0]
set_value(target, result, state, static_tools, custom_tools, authorized_imports)
else:
if len(assign.targets) != len(result):
raise InterpreterError(
f"Assign failed: expected {len(result)} values but got {len(assign.targets)}."
)
expanded_values = []
for tgt in assign.targets:
if isinstance(tgt, ast.Starred):
expanded_values.extend(result)
else:
expanded_values.append(result)
for tgt, val in zip(assign.targets, expanded_values):
set_value(tgt, val, state, static_tools, custom_tools, authorized_imports)
return result
def set_value(
target: ast.AST,
value: Any,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> None:
if isinstance(target, ast.Name):
if target.id in static_tools:
raise InterpreterError(
f"Cannot assign to name '{target.id}': doing this would erase the existing tool!"
)
state[target.id] = value
elif isinstance(target, ast.Tuple):
if not isinstance(value, tuple):
if hasattr(value, "__iter__") and not isinstance(value, (str, bytes)):
value = tuple(value)
else:
raise InterpreterError("Cannot unpack non-tuple value")
if len(target.elts) != len(value):
raise InterpreterError("Cannot unpack tuple of wrong size")
for i, elem in enumerate(target.elts):
set_value(
elem, value[i], state, static_tools, custom_tools, authorized_imports
)
elif isinstance(target, ast.Subscript):
obj = evaluate_ast(
target.value, state, static_tools, custom_tools, authorized_imports
)
key = evaluate_ast(
target.slice, state, static_tools, custom_tools, authorized_imports
)
obj[key] = value
elif isinstance(target, ast.Attribute):
obj = evaluate_ast(
target.value, state, static_tools, custom_tools, authorized_imports
)
setattr(obj, target.attr, value)
def evaluate_call(
call: ast.Call,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Any:
if not (
isinstance(call.func, ast.Attribute)
or isinstance(call.func, ast.Name)
or isinstance(call.func, ast.Subscript)
):
raise InterpreterError(f"This is not a correct function: {call.func}).")
if isinstance(call.func, ast.Attribute):
obj = evaluate_ast(
call.func.value, state, static_tools, custom_tools, authorized_imports
)
func_name = call.func.attr
if not hasattr(obj, func_name):
raise InterpreterError(f"Object {obj} has no attribute {func_name}")
func = getattr(obj, func_name)
elif isinstance(call.func, ast.Name):
func_name = call.func.id
if func_name in state:
func = state[func_name]
elif func_name in static_tools:
func = static_tools[func_name]
elif func_name in custom_tools:
func = custom_tools[func_name]
elif func_name in ERRORS:
func = ERRORS[func_name]
else:
raise InterpreterError(
f"It is not permitted to evaluate other functions than the provided tools or functions defined/imported in previous code (tried to execute {call.func.id})."
)
elif isinstance(call.func, ast.Subscript):
value = evaluate_ast(
call.func.value, state, static_tools, custom_tools, authorized_imports
)
index = evaluate_ast(
call.func.slice, state, static_tools, custom_tools, authorized_imports
)
if isinstance(value, (list, tuple)):
func = value[index]
else:
raise InterpreterError(
f"Cannot subscript object of type {type(value).__name__}"
)
if not callable(func):
raise InterpreterError(f"This is not a correct function: {call.func}).")
func_name = None
args = []
for arg in call.args:
if isinstance(arg, ast.Starred):
args.extend(
evaluate_ast(
arg.value, state, static_tools, custom_tools, authorized_imports
)
)
else:
args.append(
evaluate_ast(arg, state, static_tools, custom_tools, authorized_imports)
)
kwargs = {
keyword.arg: evaluate_ast(
keyword.value, state, static_tools, custom_tools, authorized_imports
)
for keyword in call.keywords
}
if func_name == "super":
if not args:
if "__class__" in state and "self" in state:
return super(state["__class__"], state["self"])
else:
raise InterpreterError("super() needs at least one argument")
cls = args[0]
if not isinstance(cls, type):
raise InterpreterError("super() argument 1 must be type")
if len(args) == 1:
return super(cls)
elif len(args) == 2:
instance = args[1]
return super(cls, instance)
else:
raise InterpreterError("super() takes at most 2 arguments")
else:
if func_name == "print":
state["_print_outputs"] += " ".join(map(str, args)) + "\n"
return None
else: # Assume it's a callable object
if (
(inspect.getmodule(func) == builtins)
and inspect.isbuiltin(func)
and (func not in static_tools.values())
):
raise InterpreterError(
f"Invoking a builtin function that has not been explicitly added as a tool is not allowed ({func_name})."
)
state["_trace"].append(
{"func_name": func_name, "args": args, "kwargs": kwargs}
)
return func(*args, **kwargs)
def evaluate_subscript(
subscript: ast.Subscript,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Any:
index = evaluate_ast(
subscript.slice, state, static_tools, custom_tools, authorized_imports
)
value = evaluate_ast(
subscript.value, state, static_tools, custom_tools, authorized_imports
)
if isinstance(value, str) and isinstance(index, str):
raise InterpreterError(
"You're trying to subscript a string with a string index, which is impossible"
)
if isinstance(value, pd.core.indexing._LocIndexer):
parent_object = value.obj
return parent_object.loc[index]
if isinstance(value, pd.core.indexing._iLocIndexer):
parent_object = value.obj
return parent_object.iloc[index]
if isinstance(value, (pd.DataFrame, pd.Series, np.ndarray)):
return value[index]
elif isinstance(value, pd.core.groupby.generic.DataFrameGroupBy):
return value[index]
elif isinstance(index, slice):
return value[index]
elif isinstance(value, (list, tuple)):
if not (-len(value) <= index < len(value)):
raise InterpreterError(
f"Index {index} out of bounds for list of length {len(value)}"
)
return value[int(index)]
elif isinstance(value, str):
if not (-len(value) <= index < len(value)):
raise InterpreterError(
f"Index {index} out of bounds for string of length {len(value)}"
)
return value[index]
elif index in value:
return value[index]
else:
error_message = f"Could not index {value} with '{index}'."
if isinstance(index, str) and isinstance(value, Mapping):
close_matches = difflib.get_close_matches(index, list(value.keys()))
if len(close_matches) > 0:
error_message += f" Maybe you meant one of these indexes instead: {str(close_matches)}"
raise InterpreterError(error_message)
def evaluate_name(
name: ast.Name,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Any:
if name.id in state:
return state[name.id]
elif name.id in static_tools:
return static_tools[name.id]
elif name.id in custom_tools:
return custom_tools[name.id]
elif name.id in ERRORS:
return ERRORS[name.id]
close_matches = difflib.get_close_matches(name.id, list(state.keys()))
if len(close_matches) > 0:
return state[close_matches[0]]
raise InterpreterError(f"The variable `{name.id}` is not defined.")
def evaluate_condition(
condition: ast.Compare,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> bool | object:
result = True
left = evaluate_ast(
condition.left, state, static_tools, custom_tools, authorized_imports
)
for i, (op, comparator) in enumerate(zip(condition.ops, condition.comparators)):
op = type(op)
right = evaluate_ast(
comparator, state, static_tools, custom_tools, authorized_imports
)
if op == ast.Eq:
current_result = left == right
elif op == ast.NotEq:
current_result = left != right
elif op == ast.Lt:
current_result = left < right
elif op == ast.LtE:
current_result = left <= right
elif op == ast.Gt:
current_result = left > right
elif op == ast.GtE:
current_result = left >= right
elif op == ast.Is:
current_result = left is right
elif op == ast.IsNot:
current_result = left is not right
elif op == ast.In:
current_result = left in right
elif op == ast.NotIn:
current_result = left not in right
else:
raise InterpreterError(f"Unsupported comparison operator: {op}")
if current_result is False:
return False
result = current_result if i == 0 else (result and current_result)
left = right
return result
def evaluate_if(
if_statement: ast.If,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Any:
result = None
test_result = evaluate_ast(
if_statement.test, state, static_tools, custom_tools, authorized_imports
)
if test_result:
for line in if_statement.body:
line_result = evaluate_ast(
line, state, static_tools, custom_tools, authorized_imports
)
if line_result is not None:
result = line_result
else:
for line in if_statement.orelse:
line_result = evaluate_ast(
line, state, static_tools, custom_tools, authorized_imports
)
if line_result is not None:
result = line_result
return result
def evaluate_for(
for_loop: ast.For,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> Any:
result = None
iterator = evaluate_ast(
for_loop.iter, state, static_tools, custom_tools, authorized_imports
)
for counter in iterator:
set_value(
for_loop.target,
counter,
state,
static_tools,
custom_tools,
authorized_imports,
)
for node in for_loop.body:
try:
line_result = evaluate_ast(
node, state, static_tools, custom_tools, authorized_imports
)
if line_result is not None:
result = line_result
except BreakException:
break
except ContinueException:
continue
else:
continue
break
return result
def evaluate_listcomp(
listcomp: ast.ListComp,
state: Dict[str, Any],
static_tools: Dict[str, Callable],
custom_tools: Dict[str, Callable],
authorized_imports: List[str],
) -> List[Any]:
def inner_evaluate(
generators: List[ast.comprehension], index: int, current_state: Dict[str, Any]
) -> List[Any]:
if index >= len(generators):
return [
evaluate_ast(
listcomp.elt,
current_state,
static_tools,
custom_tools,
authorized_imports,
)
]
generator = generators[index]
iter_value = evaluate_ast(
generator.iter,
current_state,
static_tools,
custom_tools,
authorized_imports,
)
result = []
for value in iter_value:
new_state = current_state.copy()
if isinstance(generator.target, ast.Tuple):
for idx, elem in enumerate(generator.target.elts):
new_state[elem.id] = value[idx]
else:
new_state[generator.target.id] = value
if all(
evaluate_ast(
if_clause, new_state, static_tools, custom_tools, authorized_imports
)
for if_clause in generator.ifs
):
result.extend(inner_evaluate(generators, index + 1, new_state))
return result
return inner_evaluate(listcomp.generators, 0, state)
def evaluate_try(
try_node: ast.Try,
state: Dict[str, Any],