ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

langchain-modal:为 Deep Agents 接入 Modal 云沙箱的官方集成指南

langchain-modal:为 Deep Agents 接入 Modal 云沙箱的官方集成指南 langchain-modal为 Deep Agents 接入 Modal 云沙箱的官方集成指南【免费下载链接】deepagentsThe batteries-included agent harness.项目地址: https://gitcode.com/GitHub_Trending/de/deepagents本篇技术指南介绍 Deep Agents 官方合作伙伴包langchain-modal它把 Modal 的云端沙箱modal.Sandbox封装为符合 Deep AgentsSandboxBackendProtocol的后端实现让 Agent 可以在 Modal 托管的隔离环境中执行 Shell 命令、上传与下载文件。阅读本文后你将掌握从安装、创建沙箱到调用execute/upload_files/download_files的完整链路并能理解其与 Deep Agents 后端协议对接的底层原理。一、背景Deep Agents 的可插拔沙箱后端Deep Agents 是一个开箱即用batteries-included的 Agent 编排框架。为了让 Agent 拥有可执行命令、读写文件的隔离运行环境Deep Agents 在 libs/deepagents/deepagents/backends/protocol.py 中定义了统一的BackendProtocol与SandboxBackendProtocolBackendProtocol定义了文件类操作read、write、edit、delete、ls、grep、glob、upload_files、download_files等SandboxBackendProtocol在BackendProtocol之上扩展了 Shell 命令执行能力execute/aexecute与沙箱唯一标识id属性面向容器、虚拟机、远程主机等隔离环境。在此基础上libs/deepagents/deepagents/backends/sandbox.py 提供了BaseSandbox基类它把文件列举、grep、glob、read 等操作全部用 Shell 命令经execute()派生实现具体后端只需要实现execute()与upload_files()两个原语。langchain-modal正是这样一款合作伙伴后端它把 Modal 的云端沙箱对象包装成一个 Deep Agents 后端让同一个 Agent 编排逻辑可以无缝运行在 Modal 的 GPU/CPU 基础设施上。二、安装langchain-modal已发布为独立的 PyPI 包推荐使用uv安装uv add langchain-modal从 pyproject.toml 可以看出包的基本约束Python 版本要求3.11,4.0同时声明了对 3.113.14 的兼容性核心依赖deepagents0.7.0,0.8.0后端协议与BaseSandbox基类以及modalModal 官方 Python SDK开发阶段仓库通过[tool.uv.sources]将deepagents指向本地libs/deepagents的可编辑安装便于在 monorepo 内联调试。包对外暴露的唯一入口是ModalSandbox类见 libs/partners/modal/langchain_modal/init.py。三、快速上手创建沙箱并执行命令libs/partners/modal/README.md 给出了最简用法把已有的modal.Sandbox实例包装为ModalSandbox即可调用execute执行命令import modal from langchain_modal import ModalSandbox sandbox ModalSandbox(modal.Sandbox.create(appmodal.App.lookup(your-app))) result sandbox.execute(echo hello) print(result.output)几个要点ModalSandbox包装的是已经存在的 Modal 沙箱构造函数是关键字参数ModalSandbox(*, sandbox: modal.Sandbox)你负责创建并持有modal.Sandbox的生命周期execute返回ExecuteResponse其中output是合并后的 stdoutstderr 文本exit_code是命令退出码truncated表示输出是否因后端限制被截断execute底层是bash -c从 sandbox.py 的实现看命令经由self._sandbox.exec(bash, -c, command, timeout...)发起。如果想要从零创建沙箱而不是App.lookup可以参考集成测试 tests/integration_tests/test_integration.py 的写法import modal def _create_modal_sandbox() - modal.Sandbox: sandbox modal.Sandbox.create( python:3.11-slim, secrets[modal.Secret.from_name(modal-token)], ) sandbox.wait() return sandbox四、ModalSandbox核心 API 详解ModalSandbox定义在 libs/partners/modal/langchain_modal/sandbox.py继承自BaseSandbox是协议SandboxBackendProtocol的一个具体实现。核心成员如下4.1 构造与标识def __init__(self, *, sandbox: modal.Sandbox) - None: self._sandbox sandbox self._default_timeout 30 * 60sandbox被包装的 Modal 沙箱实例必须是关键字参数_default_timeout默认命令超时30 分钟所有未显式指定timeout的execute调用都会使用它id属性返回self._sandbox.object_id作为该后端实例的唯一标识供上层 Agent 跟踪会话。4.2 命令执行executedef execute(self, command: str, *, timeout: int | None None) - ExecuteResponse: effective_timeout timeout if timeout is not None else self._default_timeout process self._sandbox.exec(bash, -c, command, timeouteffective_timeout) process.wait() stdout process.stdout.read() stderr process.stderr.read() output stdout or if stderr: output \n stderr if output else stderr return ExecuteResponse( outputoutput, exit_codeprocess.returncode, truncatedFalse, )需要特别注意的语义timeout0表示无限期等待这是 Modal 实现的特殊约定与SandboxBackendProtocol文档中0 可能在后端禁用超时的说明一致见 protocol.py 中SandboxBackendProtocol.execute的 docstringoutput会合并 stdout 与 stderr且优先展示 stdoutstderr 以换行符衔接便于 LLM 一次性读取完整命令结果truncated恒为False当前实现不做输出大小裁剪完整输出直接返回execute接受可选的timeout关键字因此可以通过协议层execute_accepts_timeout的运行时检测兼容所有调用方。4.3 文件上传与下载def upload_files(self, files: list[tuple[str, bytes]]) - list[FileUploadResponse]: return [self._write_file(path, content) for path, content in files] def download_files(self, paths: list[str]) - list[FileDownloadResponse]: return [self._read_file(path) for path in paths]底层_read_file/_write_file直接使用 Modal 沙箱的sandbox.open(path, rb/wb)文件句柄读写路径必须为绝对路径以/开头否则直接返回invalid_path错误码读取时对memoryview会转换为bytes字符串会按 UTF-8 编码错误码做了协议级归一化FileNotFoundError→file_not_foundModal 的FilesystemExecutionError会根据消息内容区分为is_directory提示信息包含 is a directory或file_not_found写入遇到PermissionError→permission_denied。返回的FileUploadResponse/FileDownloadResponse均为批量接口响应顺序与输入顺序一一对应每个条目携带独立的error字段允许部分成功例如{path: /app/data.txt, content: b..., error: None}与{path: /wrong/path.txt, content: None, error: file_not_found}。4.4 继承而来的文件操作由于继承BaseSandboxModalSandbox无需重新实现即可获得完整的文件操作能力包括read服务端分页读取、write先os.makedirs创建父目录再上传内容、edit服务端字符串替换、ls、grep字面量匹配、glob带**通配与花括号展开的路径匹配等。这些操作全部经由execute(bash, -c, ...)在 Modal 沙箱内部以 Python 内联脚本完成参数使用 base64 编码传递以避免 Shell 转义问题并带有MAX_MATCHES、时间预算等防失控保护。换一个后端如本地文件系统或 DockerAgent 得到的接口与行为保持一致——这正是后端协议抽象的价值所在。五、与 Deep Agents 后端协议的对接方式从类型层面看ModalSandbox满足 protocol.py 中的SandboxBackendProtocolBackendProtocol ├── 文件操作ls / read / grep / glob / write / edit / delete / upload_files / download_files └── SandboxBackendProtocol继承并扩展 ├── id 属性沙箱唯一标识 └── execute(command, *, timeout) - ExecuteResponseModalSandbox直接实现了execute()、upload_files()、download_files()与id其余文件操作由BaseSandbox基于execute()派生见 sandbox.py 模块 docstring。这意味着上层 Agent 工具层只需面向协议编程不感知底层是 Modal、Docker 还是本地文件系统ExecuteResponse为 LLM 消费做了简化输出、退出码、截断标记三要素齐全且status与exit_code分离——命令即使非零退出也被视为已执行成功模型需要阅读输出自行判断。六、测试与验证langchain-modal配套了单元测试与集成测试两类验证手段。单元测试tests/unit_tests/test_import.py 与 tests/test_import.py只做导入冒烟验证确保langchain_modal包在无 Modal 凭据的环境下也能正常导入。集成测试tests/integration_tests/test_integration.py则真正在云端运行从环境变量读取凭据MODAL_TOKEN_ID与MODAL_TOKEN_SECRET缺失时直接抛错并提示设置通过_create_modal_sandbox()创建python:3.11-slim沙箱并注入名为modal-token的 Secret用ModalSandbox(sandboxsandbox)包装后交给langchain_tests.integration_tests.SandboxIntegrationTests这一共享测试基类跑一套标准化的沙箱行为契约测试测试结束在finally中调用sandbox.terminate()释放云端资源。MakefileMakefile提供了便捷入口make test # 运行单元测试禁用网络仅允许 unix socket make integration_test # 运行集成测试需先导出 MODAL_TOKEN_ID / MODAL_TOKEN_SECRET make lint # ruff 检查 ty 类型检查 make type # 仅运行 ty 类型检查ty check langchain_modal七、版本与依赖说明当前仓库中的langchain-modal版本为0.0.6见 pyproject.toml 与 _version.py后者带有x-release-please-version注解由 release-please 在发布时与 pyproject 同步升版依赖deepagents0.7.0,0.8.0使用时请确保两者版本兼容许可证为 MITPython 3.11 可用。小结langchain-modal是 Deep Agents 官方生态中接入 Modal 云沙箱的最简路径安装一个包、包装一个modal.Sandbox即可获得协议完备的execute、文件上传下载与全套派生文件操作。结合本仓库 libs/deepagents/deepagents/backends/protocol.py 与 sandbox.py 阅读源码你可以清晰看到协议定义 → 基类派生 → 具体后端的三层设计并据此理解其他合作伙伴后端如 Daytona、Runloop、Vercel Sandbox 等的实现方式。【免费下载链接】deepagentsThe batteries-included agent harness.项目地址: https://gitcode.com/GitHub_Trending/de/deepagents创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表