翻篇收录说明
翻篇网页快照

Modal Sandbox | Pydantic Docs

https://pydantic.dev/docs/ai/harness/modal-sandbox/

最近抓取:2026-12-03 23:36:37(北京时间)

最近内容变化:2026-11-30 19:05:48(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Run a Pydantic AI agent's commands and file edits in an isolated Modal cloud sandbox instead of on your machine.

正文摘录

Modal Sandbox Run your agent’s commands and file edits in an isolated Modal cloud sandbox instead of on your machine. Source While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy. flowchart TB accTitle: Modal Sandbox: your agent's commands run in a Modal cloud sandbox accDescr: On your machine, the model calls Coder, Shell or FileSystem tools. Their ctx.workspace is a Modal cloud sandbox from ModalSandbox's get_workspace hook, reached over the Modal API with your Modal token and running until destroy(ref) or a timeout. A later run reattaches with the WorkspaceRef in the message history, and a ref to an ended sandbox gives WorkspaceUnavailableError. subgraph machine["Your machine"] model(["model"]) tools["Coder, Shell or<br/>FileSystem tools,<br/>such as run_command"] ref["WorkspaceRef<br/>in the message history,<br/>result.workspace.ref"] modal["ModalSandbox()<br/>get_workspace hook"]:::capability end sandbox["Modal cloud sandbox<br/>runs until destroy(ref)<br/>or a timeout"]:::external gone["WorkspaceUnavailableError"]:::blocked model <-->|"tool call, result"| tools tools -->|"ctx.workspace"| modal ref -.->|"a later run reattaches"| modal modal <-->|"Modal API,<br/>your Modal token"| sandbox modal -.-x|"ref to an<br/>ended sandbox"| gone classDef capability stroke:#E520E9,stroke-width:2px classDef external stroke:#0E9C86,stroke-width:2px classDef blocked stroke:#E5533D,stroke-width:2px,stroke-dasharray:4 3 Install pip uv pip uv Terminalpip install "pydantic-ai-harness[coder,modal,anthropic]" This saves your Modal credentials. In CI, set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET instead. The examples also use Coder and an Anthropic model, so they need the coder and anthropic extras and ANTHROPIC_API_KEY. Swap them for your own tools and model provider. Quick start from pydantic_ai import Agent from pydantic_ai_harness.coder import Coder from pydantic_ai_harness.modal_sandbox import ModalSandbox agent = Agent('anthropic:claude-opus-5-5', capabilities=[ModalSandbox(), Coder()]) result = agent.run_sync('Clone https://github.com/pydantic/pydantic-ai and summarize how capabilities work.') Coder’s shell and file tools now run in the sandbox. For a narrower agent, use Shell, FileSystem or your own tools on ctx.workspace. ModalSandbox warns when the agent has no Shell or FileSystem tool. If only your own tools use the sandbox, pass warn_if_no_tools=False. Coder creates it when the run starts, to load the repository’s instructions, even if no tool is called. Pass Coder(repo_context=False) to wait for the first tool call. It keeps running, and billing, after the run. See Clean up. It lives for up to 24 hours, Modal’s maximum. Pass sandbox_timeout=3600 to end it sooner, or idle_timeout= to end it when unused. The first use can take several minutes while Modal builds or pulls the image. Commands run as root in /root. Pass working_dir='/root/project' to keep the project out of the home directory. It is created on a new sandbox. The default image has Python 3.12, git and rg, but not your project’s dependencies. Bake them into a custom image, or install them before the run. It can reach the internet. For network restrictions such as Modal’s block_network, create the modal.Sandbox yourself and pass it to the run. The model can read every env value you pass. Continue in the same sandbox Pass the message history, and the next run works in the same sandbox: from pydantic_ai import Agent from pydantic_ai_harness.coder import Coder from pydantic_ai_harness.modal_sandbox import ModalSandbox agent = Agent('anthropic:claude-opus-5-5', capabilities=[ModalSandbox(), Coder()]) result = agent.run_sync('Clone https://github.com/pydantic/pydantic-ai and summarize how capabilities work.') followup = agent.run_sync( 'Which capability would you add next, and where would it live?', message_history=result.all_messages(), ) ref = result.workspace.ref # or store this, and pass `workspace=ref` to a later run The history records the sandbox as a WorkspaceRef, or “ref”: the provider’s name and the sandbox’s ID. result.workspace.ref is the same ref, for continuing without the history. If the sandbox has been terminated or has expired, the run raises WorkspaceUnavailableError. Pass workspace='new' to start over. Workspaces covers how runs find their workspace. The ref holds no credentials, so the process that reattaches needs your Modal token or a client= too. Already have a modal.Sandbox? Pass workspace=ModalSandboxBackend(sandbox=sandbox, working_dir=..., env=...) to a run. ModalSandbox’s settings don’t apply to it. A backend’s get_sandbox() returns its modal.Sandbox for Modal features the workspace API doesn’t cover. On a backend with no sandbox yet, it creates one, which Modal bills. Prepare a sandbox before the run To seed files or install packages before the agent starts, create the backend yourself, work in it through Workspace, and pass it to the run: import asyncio from pydantic_ai import Agent from pydantic_ai.workspaces import Workspace from pydantic_ai_harness.coder import Coder from pydantic_ai_harness.modal_sandbox import ModalSandbox, ModalSandboxBackend agent = Agent('anthropic:claude-opus-5-5', capabilities=[ModalSandbox(), Coder()]) async def main() -> None: backend = ModalSandboxBackend(working_dir='/root/project') try: workspace = Workspace(backend) await workspace.write_text('calc.py', 'def add(a, b):\n return a - b\n') installed = await workspace.run(['pip', 'install', 'pytest'], timeout=300) if installed.exit_code != 0: raise RuntimeError(f'pip install failed: {installed.stderr}') result = await agent.run('Fix the bug in calc.py.', workspace=backend) print(result.output) finally: ref = backend.ref # set once the sandbox exists if ref is not None: await ModalSandbox().destroy(ref) if __name__ == '__main__': asyncio.run(main()) The finally terminates the sandbox even when setup or the run fails. To keep it, store backend.ref instead. Give the agent a desktop Pass desktop=True and add ComputerUse: capabilities=[ModalSandbox(desktop=True), ComputerUse()]. The screen is 1280x800; pass a size such as desktop=(1440, 900) for another. The default image has the display’s programs but no web browser. A custom image gets them installed on first use if it can; add a browser to it if the agent needs one. The agent can type only ASCII: an action that types or presses a character such as é fails, and the model is told why. Clean up Terminate a sandbox with the ref you stored: from pydantic_ai.workspaces import WorkspaceRef from pydantic_ai_harness.modal_sandbox import ModalSandbox async def terminate_sandbox(ref: WorkspaceRef) -> None: await ModalSandbox().destroy(ref) A failed run returns no result, so terminate its sandbox in an on_run_error hook: from typing import Any import anyio from pydantic_ai import Agent, RunContext from pydantic_ai.capabilities import Hooks from pydantic_ai.run import AgentRunResult from pydantic_ai_harness.coder import Coder from pydantic_ai_harness.modal_sandbox import ModalSandbox hooks = Hooks() @hooks.on.run_error async def terminate_failed_run(ctx: RunContext[None], *, error: BaseException) -> AgentRunResult[Any]: if ctx.workspace.ref is not None: # Shielded so a deadline around the run can't cut the kill short, bounded so a hung call can't hang it. with anyio.move_on_after(30, shield=True): await ModalSandbox().destroy(ctx.workspace.ref) raise error agent = Agent('anthropic:claude-opus-5-5', capabilities=[ModalSandbox(), Coder(), hooks]) A sandbox you don’t terminate ends when its sandbox_timeout runs out, or after idle_timeout seconds without activity if you set one. See Modal’s timeouts. A sandbox whose image ignores Modal’s stop signal, such as a bare python image, can keep running for about 30 seconds after destroy returns. Find a lost sandbox If your program stops before it stores the ref, for example after a crash or Ctrl-C, the sandbox runs until its timeout. To find it: Search your logs for Created Modal sandbox <id>, logged at INFO by the pydantic_ai_harness logger. A run cancelled while Modal was still creating the sandbox also logs the id at WARNING. Then terminate it: await ModalSandbox().destroy(WorkspaceRef(provider='modal', id='<id>')). Use different credentials for each user ModalSandbox(client=modal.Client.from_credentials(token_id, token_secret)) sets one client for the capability. When each user has their own Modal account, supply the workspace from a capability of your own that takes the client from the run’s deps: from dataclasses import dataclass import modal from pydantic_ai import Agent, RunContext from pydantic_ai.capabilities import AbstractCapability from pydantic_ai.workspaces import WorkspaceBackend, WorkspaceRef from pydantic_ai_harness import Coder from pydantic_ai_harness.modal_sandbox import ModalSandboxBackend @dataclass class User: modal_client: modal.Client @dataclass class UsersModal(AbstractCapability[User]): def get_workspace(self, ctx: RunContext[User], *, ref: WorkspaceRef | None) -> WorkspaceBackend | None: if ref is not None and ref.provider != 'modal': return None return ModalSandboxBackend(ref=ref, client=ctx.deps.modal_client) agent = Agent('anthropic:claude-opus-5-5', deps_type=User, capabilities=[UsersModal(), Coder()]) Building a Modal client opens a connection, so build it before the run, not in get_workspace, which must not do I/O. Destroy a user’s sandbox with that user’s client: await ModalSandbox(client=user.modal_client).destroy(ref). With another account’s client, the sandbox isn’t found and destroy returns without an error, so the sandbox keeps billing. Under Temporal, deps are stored in the workflow’s history and a client can’t be on them. Put a user ID there, and look the client up in get_workspace on the worker. Configuration OptionWhat it doesimageImage for a new sandbox: a reg