| """ |
| tools/python_repl.py —— 工具⑧:运行 Python 代码(计算器/小程序) |
| |
| 大模型自己算数、处理表格、倒写字符串时容易出错。这个工具给它一个"草稿纸": |
| 它可以写一段 Python 代码交给本工具真正运行,再把运行结果拿回去。 |
| 适合:算术、字符串处理(如把句子倒过来)、解析表格、集合/列表运算、日期计算等。 |
| """ |
|
|
| import io |
| import contextlib |
|
|
| from langchain_core.tools import tool |
|
|
|
|
| @tool |
| def python_repl(code: str) -> str: |
| """Execute Python code and return everything it prints. Use this for any computation: |
| arithmetic, string manipulation (e.g. reversing text), parsing tables/CSV, set and list |
| operations, date math, etc. You MUST `print(...)` the values you want to see. You may |
| import standard libraries plus pandas and numpy.""" |
| buffer = io.StringIO() |
| namespace: dict = {} |
| try: |
| |
| |
| with contextlib.redirect_stdout(buffer): |
| exec(code, namespace) |
| except Exception as e: |
| |
| return f"Error: {e}\nOutput before error:\n{buffer.getvalue()}" |
| output = buffer.getvalue() |
| |
| return output if output.strip() else "Code ran successfully but printed nothing. Remember to print() your result." |
|
|