1717from typing import Any
1818
1919_SAFE_BUILTINS = {
20- "print" : print , "len" : len , "str" : str , "int" : int , "float" : float ,
21- "list" : list , "dict" : dict , "set" : set , "tuple" : tuple , "bool" : bool ,
22- "type" : type , "isinstance" : isinstance , "issubclass" : issubclass ,
23- "enumerate" : enumerate , "zip" : zip , "map" : map , "filter" : filter ,
24- "sorted" : sorted , "reversed" : reversed , "range" : range ,
25- "min" : min , "max" : max , "sum" : sum , "abs" : abs , "round" : round ,
26- "any" : any , "all" : all , "pow" : pow , "divmod" : divmod ,
27- "chr" : chr , "ord" : ord , "hex" : hex , "bin" : bin , "oct" : oct ,
28- "repr" : repr , "ascii" : ascii , "format" : format , "hash" : hash , "id" : id ,
29- "iter" : iter , "next" : next , "slice" : slice , "callable" : callable ,
30- "hasattr" : hasattr , "getattr" : getattr , "setattr" : setattr , "delattr" : delattr ,
31- "dir" : dir , "vars" : vars ,
32- "bytes" : bytes , "bytearray" : bytearray , "memoryview" : memoryview ,
33- "complex" : complex , "object" : object , "super" : super , "property" : property ,
34- "staticmethod" : staticmethod , "classmethod" : classmethod ,
35- "__import__" : __import__ , "open" : open ,
36- "Exception" : Exception , "BaseException" : BaseException ,
37- "ValueError" : ValueError , "TypeError" : TypeError , "KeyError" : KeyError ,
38- "IndexError" : IndexError , "AttributeError" : AttributeError ,
39- "FileNotFoundError" : FileNotFoundError , "OSError" : OSError , "IOError" : IOError ,
40- "RuntimeError" : RuntimeError , "NameError" : NameError , "ImportError" : ImportError ,
41- "StopIteration" : StopIteration , "AssertionError" : AssertionError ,
42- "NotImplementedError" : NotImplementedError , "ArithmeticError" : ArithmeticError ,
43- "LookupError" : LookupError , "Warning" : Warning ,
44- "input" : None , "eval" : None , "exec" : None , "compile" : None ,
45- "globals" : None , "locals" : None ,
20+ "print" : print ,
21+ "len" : len ,
22+ "str" : str ,
23+ "int" : int ,
24+ "float" : float ,
25+ "list" : list ,
26+ "dict" : dict ,
27+ "set" : set ,
28+ "tuple" : tuple ,
29+ "bool" : bool ,
30+ "type" : type ,
31+ "isinstance" : isinstance ,
32+ "issubclass" : issubclass ,
33+ "enumerate" : enumerate ,
34+ "zip" : zip ,
35+ "map" : map ,
36+ "filter" : filter ,
37+ "sorted" : sorted ,
38+ "reversed" : reversed ,
39+ "range" : range ,
40+ "min" : min ,
41+ "max" : max ,
42+ "sum" : sum ,
43+ "abs" : abs ,
44+ "round" : round ,
45+ "any" : any ,
46+ "all" : all ,
47+ "pow" : pow ,
48+ "divmod" : divmod ,
49+ "chr" : chr ,
50+ "ord" : ord ,
51+ "hex" : hex ,
52+ "bin" : bin ,
53+ "oct" : oct ,
54+ "repr" : repr ,
55+ "ascii" : ascii ,
56+ "format" : format ,
57+ "hash" : hash ,
58+ "id" : id ,
59+ "iter" : iter ,
60+ "next" : next ,
61+ "slice" : slice ,
62+ "callable" : callable ,
63+ "hasattr" : hasattr ,
64+ "getattr" : getattr ,
65+ "setattr" : setattr ,
66+ "delattr" : delattr ,
67+ "dir" : dir ,
68+ "vars" : vars ,
69+ "bytes" : bytes ,
70+ "bytearray" : bytearray ,
71+ "memoryview" : memoryview ,
72+ "complex" : complex ,
73+ "object" : object ,
74+ "super" : super ,
75+ "property" : property ,
76+ "staticmethod" : staticmethod ,
77+ "classmethod" : classmethod ,
78+ "__import__" : __import__ ,
79+ "open" : open ,
80+ "Exception" : Exception ,
81+ "BaseException" : BaseException ,
82+ "ValueError" : ValueError ,
83+ "TypeError" : TypeError ,
84+ "KeyError" : KeyError ,
85+ "IndexError" : IndexError ,
86+ "AttributeError" : AttributeError ,
87+ "FileNotFoundError" : FileNotFoundError ,
88+ "OSError" : OSError ,
89+ "IOError" : IOError ,
90+ "RuntimeError" : RuntimeError ,
91+ "NameError" : NameError ,
92+ "ImportError" : ImportError ,
93+ "StopIteration" : StopIteration ,
94+ "AssertionError" : AssertionError ,
95+ "NotImplementedError" : NotImplementedError ,
96+ "ArithmeticError" : ArithmeticError ,
97+ "LookupError" : LookupError ,
98+ "Warning" : Warning ,
99+ "input" : None ,
100+ "eval" : None ,
101+ "exec" : None ,
102+ "compile" : None ,
103+ "globals" : None ,
104+ "locals" : None ,
46105}
47106
48- RESERVED_TOOL_NAMES = frozenset ({
49- "llm_query" , "llm_query_batched" , "rlm_query" , "rlm_query_batched" ,
50- "SHOW_VARS" , "answer" , "context" , "history" ,
51- })
107+ RESERVED_TOOL_NAMES = frozenset (
108+ {
109+ "llm_query" ,
110+ "llm_query_batched" ,
111+ "rlm_query" ,
112+ "rlm_query_batched" ,
113+ "SHOW_VARS" ,
114+ "answer" ,
115+ "context" ,
116+ "history" ,
117+ }
118+ )
52119
53120
54121class _AnswerDict (dict ):
@@ -143,7 +210,10 @@ def _proxy_post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
143210 url = f"{ self .proxy_url } /rollout/{ self .rollout_id } /{ path .lstrip ('/' )} "
144211 body = json .dumps (payload ).encode ("utf-8" )
145212 req = urllib .request .Request (
146- url , data = body , headers = {"Content-Type" : "application/json" }, method = "POST" ,
213+ url ,
214+ data = body ,
215+ headers = {"Content-Type" : "application/json" },
216+ method = "POST" ,
147217 )
148218 try :
149219 with urllib .request .urlopen (req , timeout = 600 ) as resp :
@@ -153,7 +223,11 @@ def _proxy_post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
153223 detail = e .read ().decode ("utf-8" )
154224 except Exception :
155225 detail = ""
156- too_large = e .code == 413 or "Entity Too Large" in (detail or "" ) or "Entity Too Large" in (e .reason or "" )
226+ too_large = (
227+ e .code == 413
228+ or "Entity Too Large" in (detail or "" )
229+ or "Entity Too Large" in (e .reason or "" )
230+ )
157231 return {"error" : f"HTTP { e .code } : { detail or e .reason } " , "too_large" : too_large }
158232 except Exception as e :
159233 return {"error" : f"Proxy request failed: { e } " }
@@ -253,7 +327,8 @@ def execute(self, code: str) -> dict[str, Any]:
253327 final_answer = self ._last_final_answer
254328 self ._last_final_answer = None
255329 simple_keys = [
256- k for k , v in self .locals .items ()
330+ k
331+ for k , v in self .locals .items ()
257332 if not k .startswith ("_" )
258333 and k not in ("__builtins__" , "__name__" , "__doc__" )
259334 and isinstance (v , (str , int , float , bool , list , dict , tuple ))
@@ -305,7 +380,9 @@ def main() -> None:
305380 result = worker .execute (req .get ("code" , "" ))
306381 _send ({"id" : rid , "ok" : True , ** result })
307382 except BaseException as e : # noqa: BLE001
308- _send ({"id" : rid , "ok" : False , "error" : f"exec failed: { e } \n { traceback .format_exc ()} " })
383+ _send (
384+ {"id" : rid , "ok" : False , "error" : f"exec failed: { e } \n { traceback .format_exc ()} " }
385+ )
309386 elif kind == "load_context" :
310387 try :
311388 idx = worker .load_context (req .get ("payload" ), req .get ("index" ))
@@ -319,7 +396,13 @@ def main() -> None:
319396 exec (compile (code , "<bootstrap>" , "exec" ), worker .globals )
320397 _send ({"id" : rid , "ok" : True })
321398 except BaseException as e : # noqa: BLE001
322- _send ({"id" : rid , "ok" : False , "error" : f"bootstrap failed: { e } \n { traceback .format_exc ()} " })
399+ _send (
400+ {
401+ "id" : rid ,
402+ "ok" : False ,
403+ "error" : f"bootstrap failed: { e } \n { traceback .format_exc ()} " ,
404+ }
405+ )
323406 elif kind == "shutdown" :
324407 _send ({"id" : rid , "ok" : True })
325408 return
0 commit comments