File size: 1,832 Bytes
e15103f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"""
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()   # 一个"内存里的纸",用来接住代码 print 出来的所有文字
    namespace: dict = {}     # 代码运行时用的独立变量空间,避免污染本程序自身的变量
    try:
        # redirect_stdout:把代码里 print 的内容,从"打印到屏幕"改成"写进上面的 buffer"。
        # exec:真正执行那段代码字符串。
        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()   # 取出代码打印的全部内容
    # 如果代码跑成功但什么都没打印,就提醒大模型"记得用 print 输出结果"。
    return output if output.strip() else "Code ran successfully but printed nothing. Remember to print() your result."