mirror of
https://github.com/hwchase17/langchain.git
synced 2025-09-18 16:16:33 +00:00
Return output of PythonAstREPLTool when falling back to exec() (#2780)
When the code ran by the PythonAstREPLTool contains multiple statements it will fallback to exec() instead of using eval(). With this change, it will also return the output of the code in the same way the PythonREPLTool will.
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
import ast
|
||||
import sys
|
||||
from io import StringIO
|
||||
from typing import Dict, Optional
|
||||
|
||||
from pydantic import Field, root_validator
|
||||
@@ -77,8 +78,16 @@ class PythonAstREPLTool(BaseTool):
|
||||
try:
|
||||
return eval(module_end_str, self.globals, self.locals)
|
||||
except Exception:
|
||||
exec(module_end_str, self.globals, self.locals)
|
||||
return ""
|
||||
old_stdout = sys.stdout
|
||||
sys.stdout = mystdout = StringIO()
|
||||
try:
|
||||
exec(module_end_str, self.globals, self.locals)
|
||||
sys.stdout = old_stdout
|
||||
output = mystdout.getvalue()
|
||||
except Exception as e:
|
||||
sys.stdout = old_stdout
|
||||
output = str(e)
|
||||
return output
|
||||
except Exception as e:
|
||||
return str(e)
|
||||
|
||||
|
Reference in New Issue
Block a user