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

BoxLite Sandbox | Pydantic Docs

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

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

最近内容变化:2026-12-03 23:28:18(北京时间)

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

访问原网页

页面简介

Run a Pydantic AI agent's commands and file edits in a BoxLite micro-VM on your own machine, isolated from your files and processes.

正文摘录

BoxLite Sandbox Run your agent’s commands and file edits in a BoxLite micro-VM on your own machine, isolated from your files and processes, without a cloud account. 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: BoxLite Sandbox: your agent's commands run in a local micro-VM accDescr: On your machine, the model calls Coder, Shell or FileSystem tools. As ctx.workspace, BoxLiteSandbox's runtime in your process runs commands and file operations in a BoxLite micro-VM (own kernel, filesystem, kept until destroy(ref)), and a later run reattaches by the WorkspaceRef. By default the VM cannot connect to any host. With allow_internet_access=True and allowed_hosts it reaches only the listed hosts. 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"] sandbox["BoxLiteSandbox()<br/>runtime in your process"]:::capability vm["BoxLite micro-VM<br/>own kernel, filesystem<br/>kept until destroy(ref)"]:::external end allowed["hosts in allowed_hosts"]:::external other["any other host,<br/>every host by default"]:::blocked model <-->|"tool call, result"| tools tools -->|"ctx.workspace"| sandbox ref -.->|"a later run reattaches"| sandbox sandbox <-->|"commands and<br/>file operations"| vm vm -->|"allow_internet_access=True"| allowed vm -.-x|"cannot connect"| other 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,boxlite,anthropic]" The boxlite extra installs BoxLite’s Python SDK, which runs VMs in your process, with no daemon. It needs CPython 3.14 or older on one of: macOS 14 or newer on Apple silicon. Linux on x86_64 or aarch64 with glibc 2.28 or newer. The user running the agent needs read and write access to /dev/kvm. 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. Quick start from pydantic_ai import Agent from pydantic_ai_harness.boxlite_sandbox import BoxLiteSandbox from pydantic_ai_harness.coder import Coder agent = Agent('anthropic:claude-opus-5-5', capabilities=[BoxLiteSandbox(image='python:3.12-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 a VM with its own kernel and filesystem. 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. Its disk stays in BoxLite’s home directory after the run. The box stops when your process exits, but nothing deletes it. See Clean up. It has no network access. Pass allow_internet_access=True, and allowed_hosts to reach only what it needs. See Network access. Commands run as the image’s user, usually root, in /workspace, which is created if missing. Without an image, the box runs Alpine Linux, which has BusyBox but no Python, git or ripgrep. An image is any OCI image with a POSIX /bin/sh; BoxLite pulls it the first time. One process at a time can use BoxLite’s home directory (~/.boxlite, or BOXLITE_HOME). Another process gets WorkspaceUnavailableError until the first one exits. Continue in the same box Pass the message history, and the next run works in the same box, booting it again if stopped: from pydantic_ai import Agent from pydantic_ai_harness.boxlite_sandbox import BoxLiteSandbox from pydantic_ai_harness.coder import Coder agent = Agent('anthropic:claude-opus-5-5', capabilities=[BoxLiteSandbox(image='python:3.12-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 box’s name. Store it to continue later or to delete the box. If the box has been deleted, the run raises WorkspaceUnavailableError. Pass workspace='new' to start over. Workspaces covers how runs find their workspace. Prepare a box 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.boxlite_sandbox import BoxLiteSandbox, BoxLiteSandboxBackend from pydantic_ai_harness.coder import Coder agent = Agent('anthropic:claude-opus-5-5', capabilities=[BoxLiteSandbox(), Coder()]) async def main() -> None: backend = BoxLiteSandboxBackend( image='python:3.12-slim', allow_internet_access=True, allowed_hosts=['pypi.org', 'files.pythonhosted.org'], ) 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: ref = backend.ref # set once the box exists if ref is not None: await BoxLiteSandbox().destroy(ref) if __name__ == '__main__': asyncio.run(main()) The finally deletes the box even when setup or the run fails. To keep it, store backend.ref instead. BoxLiteSandbox’s settings don’t apply to a backend you pass as workspace=. Give the backend its own. For features the workspace API doesn’t cover, such as copy_in, snapshot or stop, backend.get_sandbox() returns the SDK’s boxlite.Box. Give the agent a desktop Pass desktop=True and add ComputerUse: capabilities=[BoxLiteSandbox(desktop=True, allow_internet_access=True), ComputerUse()]. The screen is 1280x800; pass a size such as desktop=(1440, 900) for another. Without an image, a new box runs debian:bookworm-slim, and its first start installs the display’s programs, with no web browser. That needs allow_internet_access=True (what that lets the box reach), with deb.debian.org in any allowed_hosts. Creating a new box without it raises UserError; for a box without network access, pass an image that has the programs. To install a browser, pass box_options={'disk_size_gb': 4}: the default disk is too small. 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 Delete a box and its disk with the ref you stored. A box that is already gone returns quietly: from pydantic_ai.workspaces import WorkspaceRef from pydantic_ai_harness.boxlite_sandbox import BoxLiteSandbox async def delete_box(ref: WorkspaceRef) -> None: await BoxLiteSandbox().destroy(ref) A failed run returns no result, so delete its box 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.boxlite_sandbox import BoxLiteSandbox from pydantic_ai_harness.coder import Coder hooks = Hooks() @hooks.on.run_error async def delete_failed_run_box(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 delete short, bounded so a hung call can't hang it. with anyio.move_on_after(30, shield=True): await BoxLiteSandbox().destroy(ctx.workspace.ref) raise error agent = Agent('anthropic:claude-opus-5-5', capabilities=[BoxLiteSandbox(image='python:3.12-slim'), Coder(), hooks]) Find a lost box If your program stops before it stores the ref, for example after a crash or Ctrl-C, the box is left behind. To find it: List boxes with await boxlite.Boxlite.default().list_info(). Or search your logs for Creating BoxLite box <id>, logged at INFO by the pydantic_ai_harness logger. Then delete it: await BoxLiteSandbox().destroy(WorkspaceRef(provider='boxlite', id='<id>')). Network access from pydantic_ai import Agent from pydantic_ai_harness.boxlite_sandbox import BoxLiteSandbox from pydantic_ai_harness.coder import Coder sandbox = BoxLiteSandbox( image='python:3.12-slim', allow_internet_access=True, allowed_hosts=['pypi.org', 'files.pythonhosted.org'], ) agent = Agent('anthropic:claude-opus-5-5', capabilities=[sandbox, Coder()]) result = agent.run_sync('Install requests and check that it imports.') With allow_internet_access=True alone, the box can connect anywhere this machine can, including your local network and services and a cloud metadata endpoint. allowed_hosts limits it to the hostnames, IP addresses and CIDR ranges you list. BoxLite’s network options describe how it matches them. Other BoxLite options box_options passes any other boxlite.BoxOptions argument to a new box. This one mounts the current directory into the box read-only: from pathlib import Path from pydantic_ai import Agent from pydantic_ai_harness.boxlite_sandbox import BoxLiteSandbox from pydantic_ai_harness.coder import Coder sandbox = BoxLiteSandbox( image='python:3.12-slim', box_options={'volumes': [(str(Path.cwd()), '/project', True)]}, ) agent = Agent('anthropic:claude-opus-5-5', capabilities=[sandbox, Coder()]) result = agent.run_sync('Summarize what the code in /project does.') Other common ones: ports, to reach a server the agent starts. secrets, for BoxLite to add credentials to the box’s HTTPS requests to the hosts you name. disk_size_gb and user. BoxLiteSandbox sets image, cpus, memory_mib, network, working_dir, env, auto_delete and the deprecated au