页面简介
Run a Pydantic AI agent's commands and file edits in a sandbox on your own OpenSandbox server, on Docker or Kubernetes.
正文摘录
OpenSandbox Run your agent’s commands and file edits in a sandbox on your own OpenSandbox server, created on first use. The server runs sandboxes as Docker containers on one machine or as pods on Kubernetes; the agent’s code is the same either way. 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: OpenSandbox: your agent's commands run in a sandbox on your OpenSandbox server accDescr: On your machine, the model calls Coder, Shell or FileSystem tools like run_command. Via ctx.workspace, OpenSandbox hands the run a sandbox created on first use on your OpenSandbox server, reached at OPEN_SANDBOX_DOMAIN. The server runs it as a Docker container or a Kubernetes pod, and the tools' commands and file operations run in it. Later runs reattach with the WorkspaceRef in the message history or result.workspace.ref, and destroy(ref) deletes the sandbox. 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"] capability["OpenSandbox(image=...)<br/>hands the run<br/>a sandbox"]:::capability end server["OpenSandbox server<br/>OPEN_SANDBOX_DOMAIN"]:::external sandbox["sandbox: Docker container<br/>or Kubernetes pod,<br/>deleted by destroy(ref)"]:::external model <-->|"tool call, result"| tools tools -->|"ctx.workspace"| capability ref -.->|"a later run reattaches"| capability capability -->|"creates, attaches"| server server -->|"runs"| sandbox capability <-->|"commands, files"| sandbox 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 Terminalpip install "pydantic-ai-harness[coder,opensandbox,anthropic]" The opensandbox extra installs the OpenSandbox SDK. The examples also use Coder and an Anthropic model, hence the coder and anthropic extras and ANTHROPIC_API_KEY; swap them for your own tools and model provider. Run a server The capability talks to an OpenSandbox server. To run one on this machine with Docker: Terminaluvx opensandbox-server init-config ~/.sandbox.toml --example docker uvx opensandbox-server Then set execd_image = "opensandbox/execd:release-1.2.0" under [runtime] in ~/.sandbox.toml. execd runs the commands inside each sandbox, and the capability needs version 1.1.1 or later. With an older one, the first operation raises WorkspaceUnavailableError. The capability reads two environment variables: OPEN_SANDBOX_DOMAIN, the server’s address. Default: localhost:8080. Requests use plain HTTP unless it starts with https://, such as https://sandbox.example.com. OPEN_SANDBOX_API_KEY, sent if your server requires a key. For Kubernetes, see Run on Kubernetes. Quick start from pydantic_ai import Agent from pydantic_ai_harness.coder import Coder from pydantic_ai_harness.opensandbox_sandbox import OpenSandbox agent = Agent('anthropic:claude-opus-5-5', capabilities=[OpenSandbox(image='python:3.13-slim'), Coder()]) result = agent.run_sync('Write a script that prints the first 10 primes, and run it.') 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. 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 after the run until you destroy it. If you set sandbox_timeout, the server also deletes it after that many seconds unused. See Clean up. Commands run as the image’s user, usually root, in /workspace, which is created if missing. The image needs a POSIX sh and the usual file utilities. Its network access is whatever the server configures. Pass allow_internet_access=False to block all outbound connections. See Network access. 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.opensandbox_sandbox import OpenSandbox agent = Agent('anthropic:claude-opus-5-5', capabilities=[OpenSandbox(image='python:3.13-slim'), Coder()]) result = agent.run_sync('Write a script that prints the first 10 primes, and run it.') followup = agent.run_sync('Now make it print the first 100.', message_history=result.all_messages()) ref = result.workspace.ref # or store this, and pass `workspace=ref` to a later run result.workspace.ref is a WorkspaceRef holding the sandbox’s id. Store it to continue later or to destroy the sandbox. If the sandbox has been destroyed, the run raises WorkspaceUnavailableError. Pass workspace='new' to start over. Workspaces covers how runs find their workspace. Whoever passes a ref runs commands in that sandbox, and the server serves every sandbox to every holder of its API key. Only pass refs your application stored itself. 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.opensandbox_sandbox import OpenSandbox, OpenSandboxBackend agent = Agent('anthropic:claude-opus-5-5', capabilities=[OpenSandbox(image='python:3.13-slim'), Coder()]) async def main() -> None: backend = OpenSandboxBackend(image='python:3.13-slim') try: workspace = Workspace(backend) await workspace.write_text('calc.py', 'def add(a, b):\n return a - b\n') install = await workspace.run(['pip', 'install', 'pytest'], timeout=300) if install.exit_code != 0: raise RuntimeError(f'pip install failed: {install.stderr}') result = await agent.run('Fix the bug in calc.py.', workspace=backend) print(result.output) finally: await backend.aclose() if backend.ref is not None: await OpenSandbox().destroy(backend.ref) if __name__ == '__main__': asyncio.run(main()) The finally destroys the sandbox even when setup or the run fails. aclose() closes the backend’s connection to the server. To keep the sandbox, store backend.ref instead. OpenSandbox’s settings don’t apply to a backend you pass as workspace=. Give the backend its own. Give the agent a desktop Pass desktop=True and add ComputerUse: capabilities=[OpenSandbox(image='debian:bookworm-slim', desktop=True), ComputerUse()]. The screen is 1280x800; pass a size such as desktop=(1440, 900) for another. When the image’s user is root, the first use installs the display’s programs that are missing with apt-get, which needs the sandbox to reach the package repositories. Passwordless sudo works only where the server allows it: the Docker runtime’s default no_new_privileges = true blocks it. Otherwise build them into the image: without the screen’s programs the first use raises WorkspaceUnavailableError naming what is missing, and without the desktop’s the screen works but stays black. On the Docker runtime, set network_mode = "bridge" under [docker] in the server’s configuration; see Security model. Use execd 1.2 or later: on older versions every screen action is slow. There’s no web browser. Install one in the image or before the run, as in Prepare a sandbox before the run with OpenSandboxBackend(..., desktop=True), or let the agent install it with Shell. 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 Destroy a sandbox, files included, with the ref you stored. A sandbox that is already gone returns quietly: from pydantic_ai.workspaces import WorkspaceRef from pydantic_ai_harness.opensandbox_sandbox import OpenSandbox async def remove_sandbox(ref: WorkspaceRef) -> None: await OpenSandbox().destroy(ref) OpenSandbox() without an image only attaches to and destroys sandboxes by ref. A failed run returns no result, so destroy 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.opensandbox_sandbox import OpenSandbox hooks = Hooks() @hooks.on.run_error async def destroy_failed_run_sandbox(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 destroy short, bounded so a hung call can't hang it. with anyio.move_on_after(30, shield=True): await OpenSandbox().destroy(ctx.workspace.ref) raise error agent = Agent('anthropic:claude-opus-5-5', capabilities=[OpenSandbox(image='python:3.13-slim'), Coder(), hooks]) To have the server clean up for you, set sandbox_timeout. The server deletes a sandbox unused for that many seconds, files included. Every operation restarts the countdown, but a single command must finish within it, so set it above your longest command. Find a lost sandbox If your program stops before it stores the ref, for example after a crash or Ctrl-C, the sandbox is left on the server. To find it: List the server’s sandboxes. Sandboxes Pydantic AI creates have a pydantic-ai-create metadata entry. Or search your logs for Created OpenSandbox sandbox <id>, logged at INFO by the pydantic_ai_harness logger. Then destroy it: await OpenSandbox().destroy(WorkspaceRef(provider='opensandbox', id='<id>')). Run on Kubernetes On a server deployed with OpenSandbox’s Helm charts, sandboxes are pods. The server creates them through OpenSandbox’s own BatchSandbox resources or through agent-sandbox, and both work the same here. Pods are reachable only inside the cluster. Either deploy the server’s ingress gateway, or let the server proxy commands