CoolFace
Apppublic

BiGuan/Agent

sourceHugging Faceupdated 4mo agoView on Hugging Face
0likes
python_repl.py34 linesDownload Raw Back to tools
1"""2tools/python_repl.py —— 工具⑧:运行 Python 代码(计算器/小程序)3 4大模型自己算数、处理表格、倒写字符串时容易出错。这个工具给它一个"草稿纸":5它可以写一段 Python 代码交给本工具真正运行,再把运行结果拿回去。6适合:算术、字符串处理(如把句子倒过来)、解析表格、集合/列表运算、日期计算等。7"""8 9import io10import contextlib11 12from langchain_core.tools import tool13 14 15@tool16def python_repl(code: str) -> str:17    """Execute Python code and return everything it prints. Use this for any computation:18    arithmetic, string manipulation (e.g. reversing text), parsing tables/CSV, set and list19    operations, date math, etc. You MUST `print(...)` the values you want to see. You may20    import standard libraries plus pandas and numpy."""21    buffer = io.StringIO()   # 一个"内存里的纸",用来接住代码 print 出来的所有文字22    namespace: dict = {}     # 代码运行时用的独立变量空间,避免污染本程序自身的变量23    try:24        # redirect_stdout:把代码里 print 的内容,从"打印到屏幕"改成"写进上面的 buffer"。25        # exec:真正执行那段代码字符串。26        with contextlib.redirect_stdout(buffer):27            exec(code, namespace)28    except Exception as e:29        # 代码出错时,连同"出错前已经打印的内容"一起返回,方便大模型排查问题。30        return f"Error: {e}\nOutput before error:\n{buffer.getvalue()}"31    output = buffer.getvalue()   # 取出代码打印的全部内容32    # 如果代码跑成功但什么都没打印,就提醒大模型"记得用 print 输出结果"。33    return output if output.strip() else "Code ran successfully but printed nothing. Remember to print() your result."34