Skip to main content
Open In ColabOpen on GitHub

Python REPL

有时,对于复杂的计算,与其直接让 LLM 生成答案,不如让 LLM 生成代码来计算答案,然后运行该代码来获得答案。为了方便地做到这一点,我们提供了一个简单的 Python REPL 来执行命令。

此接口只返回被打印出来的东西——因此,如果你想用它来计算答案,请确保它打印出答案。

caution

Python REPL 可以在主机上执行任意代码(例如,删除文件、发起网络请求)。请谨慎使用。

有关更通用的安全指南,请参阅 https://python.langchain.com/docs/security/。

from langchain_core.tools import Tool
from langchain_experimental.utilities import PythonREPL
API Reference:Tool | PythonREPL
python_repl = PythonREPL()
python_repl.run("print(1+1)")
Python REPL can execute arbitrary code. Use with caution.
'2\n'
# You can create the tool to pass to an agent
repl_tool = Tool(
name="python_repl",
description="A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.",
func=python_repl.run,
)