RocketRide tool_python 节点实战:用 RestrictedPython 沙箱为 Agent 提供受控代码执行能力
发布时间:2026/9/26 2:25:12来源:尧图网络
【免费下载链接】rocketride-serverHigh-performance AI pipeline engine with a C core and 50 Python-extensible nodes. Build, debug, and scale LLM workflows with 13 model providers, 8 vector databases, and agent orchestration, all from your IDE. Includes VS Code extension, TypeScript/Python SDKs, and Docker deployment.项目地址https://gitcode.com/gh_mirrors/ro/rocketride-server点击查看免费下载RocketRide 的tool_python节点为 Agent 提供了一个受限的进程内 Python 沙箱工具当内置工具无法满足快速算个数、转换一下数据、处理一段文本这类需求时Agent 可以直接在沙箱中执行 Python 代码而无需引入文件系统、网络或子进程级别的集成。本文基于 nodes/src/nodes/tool_python/README.md 展开结合节点源码、底层沙箱实现与单元测试完整讲解它的工作原理、python.execute工具的调用契约、配置参数以及安全边界让你能在一个 RocketRide 管道里安全地交给 Agent 一段有边界的 Python。为什么需要受限代码执行工具在 AI pipeline 中Agent 常常需要做一些小规模计算把 API 返回的数据重新整理成目标结构、对字符串做正则清洗、把时间戳换算成某个时区、或者临时算一个统计量。为每一种计算场景都内置一个专用工具并不现实而直接让 Agent 跑任意 Python 又意味着把文件系统、网络和操作系统暴露给了模型输出。tool_python的定位正是这两者之间的折中bounded code execution有边界的代码执行。它只做一件事——在一个由 RestrictedPython 构造的受限环境里执行 Agent 提供的源码它明确不做的事——不提供文件系统、网络或子进程等集成能力这类需求应交给专门为此设计的工具节点。文档的原话是Pick it for bounded code execution, not for integrations that need filesystem, network, or subprocess access.这个边界约束在节点源码里同样清晰节点暴露的唯一工具是execute且services.json中lanes为空lanes: {}意味着它没有任何数据通道纯粹以可被 Agent 调用的工具形式存在。同时它通过classType: [tool]、capabilities: [invoke]、register: filter声明了自己的工具属性见 services.json。RestrictedPython沙箱的基石RocketRide 的沙箱构建在 Python 生态的 RestrictedPython 库之上。RestrictedPython 的核心思想是不靠删掉危险函数这种易漏的方式而是在编译期改造代码——通过 AST 变换在每次属性访问、下标访问、解包、原地运算等操作处注入运行时 guard 调用从语言层面阻止越界访问。文档中将其描述为a Python library for defining and enforcing a restricted execution environment。在 RocketRide 中tool_python节点通过ai.common.sandbox.execute_sandboxed使用它见 IInstance.py 的导入语句from ai.common.sandbox import execute_sandboxed而底层沙箱的完整实现位于 packages/ai/src/ai/common/sandbox.py它由五层防护组成RestrictedPython 编译compile_restricted对 Agent 源码做 AST 变换并注入运行时 guard防止通过属性/下标访问逃逸出沙箱命名空间。Safe builtins用 RestrictedPython 的safe_builtins替换完整的__builtins__默认移除危险内建函数。仅允许名单的__import__注入一个受控的__import__只允许导入allowed_modules中明确列出的模块其余一律抛出ImportError。stdout 捕获通过StringIO支撑的print()覆盖即 RestrictedPython 的PrintCollector收集脚本输出。超时强制在 daemon 线程中执行脚本并通过thread.join(timeout)实施超时控制。RestrictedPython 由ai/common/requirements.txt作为引擎依赖引入packages/ai/src/ai/common/requirements.txt因此沙箱使用的就是真实库而非桩实现。单元测试 packages/ai/tests/ai/common/test_sandbox.py 的文档字符串也明确说明RestrictedPython is bundled with the engine via ai/common/requirements.txt, so the real library is exercised here — no mocking needed。值得注意的是沙箱还补充了两组受控能力默认允许导入的模块_DEFAULT_ALLOWED_MODULESmath、cmath、decimal、fractions、statistics、random、string、textwrap、re、json、csv、collections、itertools、functools、operator、copy、dataclasses、enum、typing、datetime、time、calendar、base64、hashlib、hmac、struct、difflib、pprint、bisect、heapq、array、numbers、unicodedata——全部是纯计算类、无文件系统/网络/OS 访问的模块sandbox.py 第 66-104 行注释明确说明这一点。额外安全内建_EXTRA_SAFE_BUILTINS因为safe_builtins极其精简连dict、list、enumerate都不含沙箱把all、any、dict、enumerate、filter、list、map、max、min、set、sum、type等无危险的常用内建重新放回支撑日常数据处理。作为工具python.execute 的调用契约节点以tool身份注册默认服务名前缀为python因此注册的工具函数是python.execute。节点本身没有数据通道no data lanesservices.json的lanes为空就是源码级证据。FunctionDescriptionpython.execute在受限沙箱中运行 Python 源码。python.execute的完整契约定义在 IInstance.py 的tool_function装饰器中含 JSON Schema 形式的input_schema与output_schema要点如下输入input_schemacode是唯一参数且必填类型必须是字符串。文档明确codeis required and must be a non-empty string。若传入的args不是 dict即工具调用不是 JSON 对象execute会直接抛出ValueError(Tool input must be a JSON object (dict))若code缺失、为空白或非字符串同样抛出ValueError(code is required and must be a non-empty string)IInstance.py。写法约定用print()产生可见输出会被捕获到响应中的stdout字段要把数据结构化返回就在脚本里给名为result的变量赋值——文档原话Use print() for visible output and assign a JSON-compatible value toresultto return it structurally。响应output_schema字段类型说明stdoutstring脚本print()产生的输出经捕获与截断stderrstring脚本抛异常时的 tracebackexit_codeinteger0 成功1 异常-1 超时timed_outboolean脚本是否因超时被杀死result任意脚本中result变量的值JSON 兼容时原样返回文档特别强调被阻止的导入或非法代码都会通过这个响应结构上报而不是让工具本身抛异常——blocked imports or invalid code are reported through that result。对照 IInstance.pyexecute只做输入校验随后直接return execute_sandboxed(...)把语法错误、编译策略拦截、运行时异常、超时全部折叠进返回 dict 的exit_code/stderr/timed_out字段因此对 Agent 而言调用永远有结果。一个最小调用示例对应测试 test_sandbox.py 的行为{ code: print(\hello world\)\nresult 1 2 }对应的响应大致为{stdout: hello world\n, stderr: , exit_code: 0, timed_out: false, result: 3}。返回值序列化的细节只有str | int | float | bool | list | dict | None这些 JSON 兼容类型会被原样放入result其他对象例如frozenset会退化为repr(...)字符串返回。这一点由沙箱源码sandbox.py与参数化测试 test_sandbox.py 共同印证——frozenset走 repr 回退路径None的结果则直接从响应中省略。配置参数详解节点的四个配置字段定义在 services.json 的fields中并通过 IGlobal.py 在全局初始化阶段解析。文档给出的建议是Start with the default timeout and no additional modules. The server name is normally only changed to avoid a tool-name collision.Execution timeout执行超时秒字段类型默认值范围tool_python.timeoutinteger201–1200缺省或非法输入时使用沙箱默认值 20 秒即_TIMEOUT 20。配置值会被钳制到 1–1200 秒区间。源码实现在 IGlobal.py 的_parse_timeout先int(raw)尝试转换失败则返回None走默认成功则max(1, min(value, 1200))钳制。文档的实践提醒非常关键Raise it only for a computation that genuinely needs longer, because an agent call remains occupied until the sandbox returns or times out——调大超时会让 Agent 的这一轮工具调用一直占用直到沙箱返回或超时因此不要随意调大。Additional Allowed Modules额外允许模块字段类型默认值tool_python.allowedModulesarray元素为{ moduleName: ... }对象空仅内置默认模块每个配置的模块名都会被加入沙箱的导入白名单与内置默认模块取并集。文档建议Keep this list empty for the narrowest environment; add a module only when the agent needs it and you accept the capabilities that module exposes.工具描述会动态生成当前生效的允许导入列表见 IInstance.py 的descriptionlambda self: ...Allowed imports: {sorted(_DEFAULT_ALLOWED_MODULES | allowed_modules)}Agent 据此决定能否 import白名单之外的导入一律抛ImportError。解析逻辑在 IGlobal.py 的_parse_allowed_modules字段缺失返回None用默认集字段存在时逐个提取row.get(moduleName)空串会被过滤。其余两个字段字段类型默认值说明tool_python.serverNamestringpython工具命名空间前缀serverName.execute。通常只在避免工具名冲突时修改。tool_python.moduleNamestring模块名节点注册用元数据。在 services.json 中tool_python.serverName被标记为hidden: true且默认python与文档server name 一般不变的建议一致UI 上可见的配置项只有timeout与allowedModules见shape段的properties: [type, tool_python.timeout, tool_python.allowedModules]。沙箱边界什么会被拦截文档Sandbox boundary一节指出节点使用 RestrictedPython 的受限编译器与安全内建且工具调用必须是 JSON 对象code缺失、空白或非字符串会在执行前就触发校验错误。对应到沙箱实现以下行为会被明确拦截或特殊处理均有测试佐证见 packages/ai/tests/ai/common/test_sandbox.py语法错误compile_restricted抛SyntaxError→ 返回exit_code: 1、stderr携带错误信息测试test_invalid_syntax_is_reported。编译策略违规compile_restricted返回None→ 返回stderr Code blocked by RestrictedPython compilation policy.、exit_code: 1。白名单外导入import os默认抛ImportError测试test_os_import_blocked只有显式把os加入allowed_modules后才会放行测试test_os_import_allowed_with_module。危险属性逃逸例如result (1).__class__这类属性访问被 guard 拦截测试test_dangerous_attribute_access_blocked。运行时异常如1 / 0→ traceback 进入stderrexit_code: 1测试test_zero_division。SystemExitraise SystemExit(2)会把整数码透传到exit_code无参数SystemExit视为成功带字符串的SystemExit进入stderr且exit_code: 1对应 sandbox.py 的_run内部分支与三个相关测试。超时daemon 线程join(timeout)后线程仍存活 →timed_out: True、stderr记录[Execution timed out after Ns]、exit_code: -1。stdout/stderr 截断输出超过 50 KB_MAX_OUTPUT 51200时保留头尾并在中间插入截断标记_truncatesandbox.py。另外还有一个值得了解的实现细节由于 RestrictedPython 的compile_restricted对任何只打印不读取 collector 变量的代码都会发出SyntaxWarning沙箱在编译时用warnings.catch_warnings()精确屏蔽了这一条噪音警告并用一把_COMPILE_LOCK串行化编译步骤避免并发编译时全局 warning filter 的竞态sandbox.py。在管道中挂载这个工具把tool_python挂到 Agent 上就是在管道文件里新增一个tool_python类型的节点并把它的control指向要使用该工具的 Agent 节点。仓库中的 examples/agent-workflow.pipe 提供了一个现成示例第 52-59 行一个id: tool_python_1、provider: tool_python、config: { type: tool_python }的节点通过control: [{ classType: tool, from: agent_rocketride_1 }]挂载到agent_rocketride_1下。需要调参时在config中追加字段即可例如{ id: tool_python_1, provider: tool_python, config: { type: tool_python, tool_python.timeout: 60, tool_python.allowedModules: [ { tool_python.moduleName: numpy } ] }, control: [ { classType: tool, from: agent_rocketride_1 } ] }注意allowedModules里新增的非默认模块如果未安装沙箱的受限__import__会在首次导入时尝试用 pip 自动安装_pip_installsandbox.py随后使 import 缓存失效这个自动安装只对不在默认白名单内的模块触发且只对已被管理员显式加入白名单的模块执行。什么时候用它什么时候不用结合文档定位与实现可以给出清晰的选择建议适合tool_python的场景数学计算math/statistics/decimal、数据重塑json/csv/collections/itertools、文本处理re/string/textwrap/difflib、时间日期运算datetime/time/calendar、编码散列base64/hashlib/hmac、以及其他能在白名单内完成、且输出可 JSON 序列化的有界计算。不适合的场景需要访问文件系统、发起网络请求、启动子进程或需要os/sys/subprocess/socket等系统级能力的集成任务——文档明确建议为这类需求选择目的明确的集成工具例如仓库中同样注册为工具的tool_http_request见 examples/agent-workflow.pipe 第 43-50 行的用法。同时应牢记小工具不做大事需要长时间运行的脚本请三思是否真的有必要调高超时因为每次python.execute调用都会占用 Agent 的调用回合直到沙箱返回。结语tool_python是 RocketRide 工具库中一个小而精的节点它把 RestrictedPython 的受限编译、安全内建与白名单导入封装成一个对 Agent 友好的python.execute工具让 Agent 在绝不触碰文件系统、网络与子进程的前提下完成大量日常的数据计算与转换。理解它的五层防护受限编译 → 安全内建 → 白名单__import__→ stdout 捕获 → 超时看门狗、result变量的结构化返回约定以及timeout/allowedModules两个核心配置的钳制与并集语义你就能在管道里放心地把它交给 Agent同时把风险严格控制在有边界的代码执行之内。赞分享【免费下载链接】rocketride-serverHigh-performance AI pipeline engine with a C core and 50 Python-extensible nodes. Build, debug, and scale LLM workflows with 13 model providers, 8 vector databases, and agent orchestration, all from your IDE. Includes VS Code extension, TypeScript/Python SDKs, and Docker deployment.项目地址https://gitcode.com/gh_mirrors/ro/rocketride-server点击查看免费下载相关推荐RocketRide tool_daytona为 Agent 提供隔离、可自愈的 Daytona 云沙箱执行工具RocketRide tool_daytona为 Agent 提供隔离、可自愈的 Daytona 云沙箱执行工具 tool_daytona 是 RocketRMicrosoft Agent Framework 如何为 Agent 启用 CodeAct 代码执行沙箱Microsoft Agent Framework 如何为 Agent 启用 CodeAct 代码执行沙箱 如果你的 Agent 需要执行模型生成的代码做数人工智能AI Agent多智能体Agent 工作流RocketRide tool_gcs 节点实战为 Agent 提供 Google Cloud Storage 只读访问RocketRide tool_gcs 节点实战为 Agent 提供 Google Cloud Storage 只读访问 本篇技术指南以 RocketRide上一篇Sinon spy.getCall(n) 完全指南按索引精确访问间谍调用的底层实现与实战下一篇Element UI PageHeader 页头组件实战指南从基础用法到源码级实现解析创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
网站建设高端定制企业官网