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

Workspaces | Pydantic Docs

https://pydantic.dev/docs/ai/core-concepts/workspace/

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

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

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

访问原网页

页面简介

正文摘录

Workspaces A workspace is where your agent runs commands and reads and writes files: a directory on your machine, a container, or a cloud sandbox. Tools reach it through ctx.workspace, so the same tools work in any of them, and you switch by changing one capability. Give an agent a workspace workspace_agent.pyimport asyncio from pydantic_ai import Agent, ModelRetry, RunContext from pydantic_ai.capabilities import LocalWorkspace from pydantic_ai.workspaces import WorkspaceError agent = Agent( 'anthropic:claude-sonnet-5-5', capabilities=[LocalWorkspace('.')], ) @agent.tool async def execute(ctx: RunContext, command: list[str]) -> str: """Run a command in the project directory.""" try: result = await ctx.workspace.run(command, timeout=60) except WorkspaceError as error: # e.g. a timeout, or a read-only workspace raise ModelRetry(str(error)) return result.stdout if result.exit_code == 0 else f'[exit {result.exit_code}] {result.stderr}' async def main() -> None: result = await agent.run('Write fizzbuzz to fizzbuzz.py and run it.') print(result.output) #> fizzbuzz.py is written and runs clean. if __name__ == '__main__': asyncio.run(main()) LocalWorkspace('.') gives every run the current directory. Commands start there and relative paths resolve against it. The directory must already exist. ctx.workspace.run(...) returns the command’s exit_code, stdout and stderr. A failing command is a normal result, so the model sees what went wrong. timeout=60 stops a stuck command with a WorkspaceTimeoutError, which carries the output so far. The clock starts once the sandbox is ready, so creating it doesn’t count. Turning any WorkspaceError into ModelRetry lets the model try something else. Without it, the error ends the run. You rarely write these tools yourself: Coder, Shell and FileSystem from the Pydantic AI Harness give the model file, search and shell tools that work in whatever workspace the run has. Run it in a sandbox LocalWorkspace runs the model’s commands on your machine, as you. To run them somewhere isolated, swap it for a sandbox. Your tools, such as the execute tool above or Coder here, now run there: 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 run its tests.') The sandbox is created the first time the run uses it: With Coder, that’s when the run starts, because Coder loads the repository’s instructions. Pass Coder(repo_context=False) to wait for the first tool call instead. A durable run also creates it when the run starts. The sandbox keeps running after the run until you delete it or its provider stops it. Cleaning up shows how to handle that. Supported workspaces LocalWorkspace and WindowsWorkspace come with pydantic-ai. The rest come with Pydantic AI Harness, each behind its own install extra. WorkspaceWhere commands runIsolated from your machineYou needLocalWorkspaceA directory on this machine (macOS, Linux)NoNothingWindowsWorkspaceA directory on this machine, in PowerShellNoWindowsDocker ContainerA local Docker or Podman containerYes, sharing your machine’s kernelDocker or PodmanSmol SandboxA smolvm microVM on this machineYesApple silicon Mac, or Linux with KVMBoxLite SandboxA BoxLite micro-VM on this machine, with an optional egress allow-listYesApple silicon Mac, or Linux with KVMOpenSandboxA sandbox on your own OpenSandbox server, on Docker or KubernetesYesAn OpenSandbox serverKubernetes SandboxA pod from an agent-sandbox warm poolYesA cluster with agent-sandboxModal SandboxA Modal cloud sandboxYesA Modal accountE2B SandboxAn E2B cloud sandboxYesAn E2B accountDaytona SandboxA Daytona cloud sandboxYesA Daytona accountRender SandboxA Render sandboxYesA Render workspace with Sandboxes accessSprites SandboxA persistent Fly.io SpriteYesA Sprites API tokenboxd SandboxA boxd cloud machineYesA boxd accountSSH WorkspaceAnother machine, over your ssh clientYes, on another host, but not sandboxed there: commands run as your SSH userSSH accessBubblewrapped WorkspaceWraps another workspace and runs its commands in Linux bwrapBest effort, not a security boundaryLinux with bwrap on that host Other packages implement the same interface: pydantic-ai-backend, a community package by Vstorm, provides workspaces backed by Kubernetes pods, Docker, Daytona, a sandboxd service that holds the Docker socket for you, and in-memory documents you keep in your own database. To list a package here, open a pull request. For anything else, write a backend: one class that runs a command, plus a test suite that checks it behaves like the others. Custom Workspaces also shows how to: Supply a workspace from a capability to give each user their own. Mark who wrote its files, for the whole workspace or by path, so the model doesn’t take a third-party file’s text as your instructions. Wrap a workspace to add a policy of your own. Your machine or a sandbox LocalWorkspace isolates nothing: a command can read and change anything you can, and the directory only sets where commands start. Use it for your own, trusted work, and a sandbox for code you don’t trust. A sandbox is a container or a VM. A container shares your machine’s kernel, so a kernel flaw can let a command escape it. A VM runs its own kernel, which makes it the stronger boundary for code you don’t trust. Docker’s Containers are not VMs explains the difference. Commands in a LocalWorkspace get your PATH, HOME, LANG, LC_ALL and LC_CTYPE, and nothing else from the agent’s environment, so your API keys don’t reach the commands the model runs. Pass what they need with env=, never the whole os.environ: from pydantic_ai import Agent from pydantic_ai.capabilities import LocalWorkspace agent = Agent( 'anthropic:claude-sonnet-5-5', capabilities=[LocalWorkspace('.', env={'UV_OFFLINE': '1'})], ) Using the workspace in tools ctx.workspace has the same methods in every workspace: run runs a command. read_text and write_text read and write text. read_bytes and write_bytes read and write exact bytes. Writing creates missing parent directories. list_dir, stat, exists, make_dir and remove work with directories and entries. file_tools.pyfrom pydantic_ai import ModelRetry, RunContext from workspace_agent import agent @agent.tool async def read_source(ctx: RunContext, path: str) -> str: """Read a text file from the project.""" try: return await ctx.workspace.read_text(path) except FileNotFoundError: raise ModelRetry(f'{path} does not exist.') @agent.tool async def save_notes(ctx: RunContext, notes: str) -> str: """Save notes for later steps.""" await ctx.workspace.write_text('NOTES.md', notes) return 'Saved to NOTES.md.' Relative paths resolve against the working directory. It is a starting point, not a boundary: .. and absolute paths reach the rest of the environment. run(..., cwd='subdir') starts one command in another directory, relative to the working directory. The directory must already exist. Sandbox providers use different default users and directories, so prefer relative paths, or set working_dir= on the sandbox. A bad path raises the usual error, such as FileNotFoundError or IsADirectoryError. Raise ModelRetry from it so the model can try again. Uncaught, it ends the run. On Temporal, it follows the retry policy instead. An environment that is gone, such as a sandbox deleted during a command, raises WorkspaceUnavailableError and ends the run. A command killed by a signal while its environment stays live returns its exit code instead. Pick up where you left off Pass the message history to the next run, and it continues in the same workspace. With a sandbox, the files and installed packages from the first run are still there: from workspace_agent import agent async def main() -> None: first = await agent.run('Write fizzbuzz to fizzbuzz.py and run it.') await agent.run('Now add a test for it.', message_history=first.all_messages()) This works because each model response records which workspace it ran in. The record is a WorkspaceRef, a reference (or “ref”) holding the provider’s name and the environment’s ID, stored on workspace_ref. It is saved with the messages, so this works however you store them: from pydantic_ai import ModelMessagesTypeAdapter from workspace_agent import agent async def main() -> None: first = await agent.run('Write fizzbuzz to fizzbuzz.py and run it.') print(first.response.workspace_ref == first.workspace.ref) #> True saved = first.all_messages_json() # store it in your database history = ModelMessagesTypeAdapter.validate_json(saved) await agent.run('Now add a test for it.', message_history=history) To continue without the history, for example in a new conversation about the same project, save the reference and pass it as workspace=: from workspace_agent import agent async def main() -> None: first = await agent.run('Write fizzbuzz to fizzbuzz.py and run it.') ref = first.workspace.ref # a small dataclass: `provider` and `id` await agent.run('Explain what fizzbuzz.py does.', workspace=ref) A sandbox’s ref is None until the run first uses it. A run that never touches the workspace records no reference, and a later turn that doesn’t use it keeps the earlier one. If the sandbox a reference names is gone, the run raises WorkspaceUnavailableError instead of starting over in an empty one. Pass workspace='new' to start over on purpose. sanitize_messages and the UI adapters strip references from history a client sends you, so a client can’t choose where your agent works. Save the reference on your server and pass it as workspace=. Cleaning up Pydantic AI never deletes an environment. A sandbox keeps running, and billing, after the run until you delete it or its provider’s lifetime settings stop it. Each sandbox page shows how to delete one. After a successful run that used the sandbox, result.workspace.ref names it, so you can continue in it o