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

Improved query, print & exception handling in REPL Tool #3215

Closed
wants to merge 3 commits into from
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 13 additions & 12 deletions langchain/tools/python/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import ast
import sys
import re
from io import StringIO
from contextlib import redirect_stdout
from typing import Dict, Optional

from pydantic import Field, root_validator
Expand Down Expand Up @@ -68,26 +70,25 @@ def _run(self, query: str) -> str:
"""Use the tool."""
try:
if self.sanitize_input:
# Remove the triple backticks from the query.
query = query.strip().strip("```")
# Remove backticks & python (if llm mistakes python console as terminal) from query
query = re.sub(r"(?i:python)|`", "", query).strip()
tree = ast.parse(query)
module = ast.Module(tree.body[:-1], type_ignores=[])
exec(ast.unparse(module), self.globals, self.locals) # type: ignore
module_end = ast.Module(tree.body[-1:], type_ignores=[])
module_end_str = ast.unparse(module_end) # type: ignore
io_buffer = StringIO()
try:
return eval(module_end_str, self.globals, self.locals)
with redirect_stdout(io_buffer):
ret = eval(module_end_str, self.globals, self.locals)
if ret is None:
return io_buffer.getvalue()
else:
return ret
except Exception:
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
try:
with redirect_stdout(io_buffer):
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
return io_buffer.getvalue()
except Exception as e:
return "{}: {}".format(type(e).__name__, str(e))

Expand Down