A tool for running python code snippet.
| 97 | |
| 98 | |
| 99 | class PythonInterpreter(BaseModel): |
| 100 | """A tool for running python code snippet.""" |
| 101 | |
| 102 | name: str = "python_interpreter" |
| 103 | description: str = ( |
| 104 | "A Python shell. Use this to execute python commands. " |
| 105 | ) |
| 106 | description_zh: str = ( |
| 107 | "Python 交互式 shell。使用此工具来执行 Python 代码。" |
| 108 | ) |
| 109 | globals: Optional[Dict] = Field(default_factory=dict) |
| 110 | locals: Optional[Dict] = Field(default_factory=dict) |
| 111 | sanitize_input: bool = True |
| 112 | max_length: int = 500 |
| 113 | is_evalf: bool = True |
| 114 | args_schema: Type[BaseModel] = PythonInputs |
| 115 | use_signals: bool = True # need to set False for async run |
| 116 | |
| 117 | @root_validator(pre=True) |
| 118 | def validate_python_version(cls, values: Dict) -> Dict: |
| 119 | """Validate valid python version.""" |
| 120 | if sys.version_info < (3, 9): |
| 121 | raise ValueError( |
| 122 | "This tool relies on Python 3.9 or higher " |
| 123 | "(as it uses new functionality in the `ast` module, " |
| 124 | f"you have Python version: {sys.version}" |
| 125 | ) |
| 126 | return values |
| 127 | |
| 128 | def _base_run( |
| 129 | self, |
| 130 | query: str, |
| 131 | ) -> str: |
| 132 | """Use the tool.""" |
| 133 | def _sub_run(bodys): |
| 134 | io_buffer = StringIO() |
| 135 | module = ast.Module(bodys[:-1], type_ignores=[]) |
| 136 | exec(ast.unparse(module), self.globals, self.locals) # type: ignore |
| 137 | module_end = ast.Module(bodys[-1:], type_ignores=[]) |
| 138 | module_end_str = ast.unparse(module_end) # type: ignore |
| 139 | |
| 140 | try: |
| 141 | with redirect_stdout(io_buffer): |
| 142 | ret = eval(module_end_str, self.globals, self.locals) |
| 143 | if ret is None: |
| 144 | return True, truncate_string(io_buffer.getvalue(), max_length=self.max_length, is_evalf=self.is_evalf) |
| 145 | else: |
| 146 | return True, truncate_string(ret, max_length=self.max_length, is_evalf=self.is_evalf) |
| 147 | except Exception: |
| 148 | with redirect_stdout(io_buffer): |
| 149 | exec(module_end_str, self.globals, self.locals) |
| 150 | return False, truncate_string(io_buffer.getvalue(), max_length=self.max_length, is_evalf=self.is_evalf) |
| 151 | |
| 152 | try: |
| 153 | if self.sanitize_input: |
| 154 | query = sanitize_input(query) |
| 155 | tree = ast.parse(query) |
| 156 | print_indexs = find_print_node(tree.body) |
no outgoing calls
no test coverage detected