以编程方式使用文档

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

此接口只会返回打印的内容——因此,如果您想用它来计算答案,请确保让它打印出答案。

from langchain.tools import tool
from langchain_experimental.utilities import 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
@tool
def python_repl_tool(code: str) -> str:
    """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(...)`.
    """
    return python_repl.run(code)