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

E2B Sandbox | Pydantic Docs

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

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

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

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

访问原网页

页面简介

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

正文摘录

E2B Sandbox Run your agent’s commands and file edits in an isolated E2B 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: E2B Sandbox: your agent's commands run in an E2B cloud sandbox accDescr: On your machine, the model calls Coder, Shell or FileSystem tools such as run_command. Via ctx.workspace, E2BSandbox's get_workspace gives the run an E2B cloud sandbox over the E2B API with E2B_API_KEY, paused at its timeout and killed by destroy(ref). A later run reattaches with the WorkspaceRef in the message history or result.workspace.ref and resumes the sandbox if paused. 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"] e2b["E2BSandbox()<br/>get_workspace gives<br/>the run an E2B sandbox"]:::capability end sandbox["E2B cloud sandbox<br/>paused at its timeout,<br/>killed by destroy(ref)"]:::external model <-->|"tool call, result"| tools tools -->|"ctx.workspace"| e2b ref -.->|"a later run reattaches<br/>and resumes it if paused"| e2b e2b <-->|"E2B API, E2B_API_KEY"| sandbox classDef capability stroke:#E520E9,stroke-width:2px classDef external stroke:#0E9C86,stroke-width:2px Install pip uv Terminalpip install "pydantic-ai-harness[coder,e2b,anthropic]" Set E2B_API_KEY to your E2B API key. 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.e2b_sandbox import E2BSandbox agent = Agent('anthropic:claude-opus-5-5', capabilities=[E2BSandbox(), 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. 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 pauses after 1 hour, and the next run resumes it. That is sandbox_timeout=3600, the most E2B’s Hobby plan allows. On a Pro plan, pass up to sandbox_timeout=86400. Pass idle_timeout=600 to pause it about 10 minutes after its last command or file operation instead. Each operation extends its lifetime as it starts, up to sandbox_timeout from the run’s first use; under durable execution, from each activity’s first use. Model turns count as idle, and one command must finish within it, so use minutes. A later run with idle_timeout shortens a longer lifetime to idle_timeout. On a Pro plan, E2BSandbox(sandbox_timeout=86400, idle_timeout=600) keeps a busy run’s sandbox for up to a day and pauses a finished one after 10 minutes. Commands start in /home/user. Pass working_dir='/home/user/project' to keep the project out of the home directory. It is created on a new sandbox. The default template has Python and git, but not your project’s dependencies or ripgrep. A template is the image a new sandbox starts from. Bake them into your own E2B template and pass template='my-template', or install them before the run. Continue in the same sandbox Pass the message history, and the next run works in the same sandbox, resuming it if paused: from pydantic_ai import Agent from pydantic_ai_harness.coder import Coder from pydantic_ai_harness.e2b_sandbox import E2BSandbox agent = Agent('anthropic:claude-opus-5-5', capabilities=[E2BSandbox(), 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 killed, 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 E2B_API_KEY or a client= too. Already have an e2b.AsyncSandbox? Pass workspace=E2BSandboxBackend(sandbox=sandbox, working_dir=..., env=..., idle_timeout=...) to a run. E2BSandbox’s settings don’t apply to it. 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.e2b_sandbox import E2BSandbox, E2BSandboxBackend agent = Agent('anthropic:claude-opus-5-5', capabilities=[E2BSandbox(), Coder()]) async def main() -> None: backend = E2BSandboxBackend(working_dir='/home/user/project') 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 sandbox exists if ref is not None: await E2BSandbox().destroy(ref) if __name__ == '__main__': asyncio.run(main()) The finally kills 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=[E2BSandbox(desktop=True), ComputerUse()]. The screen is 1280x800; pass a size such as desktop=(1440, 900) for another. The size applies when the screen first starts. A new sandbox uses E2B’s desktop template, a desktop with a terminal and Google Chrome. Your own template needs the display’s programs, which the first use installs if it can, and startxfce4, which it doesn’t. Without startxfce4, the screen stays black until a program opens a window. When sandbox_timeout runs out, a run that is still going fails. Set it longer than your longest task. The agent can type only ASCII: an action that types or presses a character such as é fails, and the model is told why. The Print key opens XFCE’s screenshot dialog instead of reaching the app. Clean up Kill a sandbox with the ref you stored. This works on a paused sandbox too, without resuming it: from pydantic_ai.workspaces import WorkspaceRef from pydantic_ai_harness.e2b_sandbox import E2BSandbox async def kill_sandbox(ref: WorkspaceRef) -> None: await E2BSandbox().destroy(ref) A failed run returns no result, so kill 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.e2b_sandbox import E2BSandbox 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 E2BSandbox().destroy(ctx.workspace.ref) raise error agent = Agent('anthropic:claude-opus-5-5', capabilities=[E2BSandbox(), Coder(), hooks]) A sandbox you don’t kill pauses when its sandbox_timeout runs out, or its idle_timeout if you set one. See E2B’s sandbox lifecycle. 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 behind. To find it: Search your logs for Created E2B sandbox <id>, logged at INFO by the pydantic_ai_harness logger. If the run stopped before E2B replied, there’s no log line. Look in the E2B dashboard. Then kill it: await E2BSandbox().destroy(WorkspaceRef(provider='e2b', id='<id>')). Use different credentials for each user E2BSandbox(client=E2B(api_key=...)) sets one client for the capability. When each user has their own E2B account, supply the workspace from a capability of your own that builds the client from the run’s deps: from dataclasses import dataclass from e2b import E2B from pydantic_ai import Agent, RunContext from pydantic_ai.capabilities import AbstractCapability from pydantic_ai.workspaces import WorkspaceBackend, WorkspaceRef from pydantic_ai_harness.coder import Coder from pydantic_ai_harness.e2b_sandbox import E2BSandboxBackend @dataclass class User: e2b_api_key: str @dataclass class UsersE2B(AbstractCapability[User]): def get_workspace(self, ctx: RunContext[User], *, ref: WorkspaceRef | None) -> WorkspaceBackend | None: if ref is not None and ref.provider != 'e2b': return None if not ctx.deps.e2b_api_key: # E2B would fall back to `E2B_API_KEY` raise ValueError('This user has no E2B API key.') return E2BSandboxBackend(client=E2B(api_key=ctx.deps.e2b_api_key), ref=ref) agent = Agent('anthropic:claude-opus-5-5', deps_type=User, capabilities=[UsersE2B(), Coder()]) E2B’s client falls back to E2B_API_KEY when its key is empty, so check for a key first, as above, or a user without one runs on that account. Destroy a user’s sandbox with that user’s key: await E2BSandbox(client=E2B(api_key=user.e2b_api_key)).destroy(ref). With another account’s client, the sandbox isn’t found and destroy returns without an error, so the sandbox keeps billing. Under Temp