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

Docker Container | Pydantic Docs

https://pydantic.dev/docs/ai/harness/docker-container/

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

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

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

访问原网页

页面简介

Run a Pydantic AI agent's commands and file edits in a local Docker or Podman container, created on first use.

正文摘录

Docker Container Run your agent’s commands and file edits in a local Docker or Podman container, created on first use, away from your machine’s files and processes. 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: Docker Container: your agent's commands run in a local container accDescr: The model calls Coder, Shell or FileSystem tools, such as run_command, and gets results. Through ctx.workspace the tools use DockerContainer, whose get_workspace hands the run a container. DockerContainer runs docker exec and gets output in a local Docker container, created on first use and kept until destroy(ref), where docker_args can mount a project directory on your machine. model(["model"]) tools["Coder, Shell or<br/>FileSystem tools,<br/>such as run_command"] sandbox["DockerContainer()<br/>get_workspace hands<br/>the run a container"]:::capability project["project directory<br/>on your machine"] container["local Docker container<br/>created on first use,<br/>kept until destroy(ref)"]:::external model <-->|"tool call, result"| tools tools -->|"ctx.workspace"| sandbox sandbox <-->|"docker exec, output"| container project -.->|"mount via docker_args"| container classDef capability stroke:#E520E9,stroke-width:2px classDef external stroke:#0E9C86,stroke-width:2px Install pip uv Terminalpip install "pydantic-ai-harness[coder,anthropic]" The capability runs the docker CLI already on your machine, so it needs no extra of its own. 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.coder import Coder from pydantic_ai_harness.docker_container import DockerContainer agent = Agent('anthropic:claude-opus-5-5', capabilities=[DockerContainer(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 container. 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. Nothing removes it, and there is no idle or lifetime limit. See Clean up. It starts empty. To work on files on your machine, mount a project directory. 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; Docker pulls it the first time. It reaches the internet, your local network and services on this machine through Docker’s default bridge. Pass allow_internet_access=False to run it with --network none. The image’s entrypoint doesn’t run, so a service the image would start on boot isn’t running; start it with a command. Continue in the same container Pass the message history, and the next run works in the same container, starting it if stopped: from pydantic_ai import Agent from pydantic_ai_harness.coder import Coder from pydantic_ai_harness.docker_container import DockerContainer agent = Agent('anthropic:claude-opus-5-5', capabilities=[DockerContainer(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 container’s name. Store it to continue later or to remove the container. If the container has been removed, 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 container, so only pass refs your application stored itself. DockerContainer refuses a container without its ai.pydantic.workspace=true label, so a ref can’t reach other containers on the daemon. Anyone who can run docker can add that label, though. Prepare a container 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.docker_container import DockerContainer, DockerContainerBackend agent = Agent('anthropic:claude-opus-5-5', capabilities=[DockerContainer(image='python:3.13-slim'), Coder()]) async def main() -> None: backend = DockerContainerBackend(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: ref = backend.ref # set once the container is being created if ref is not None: await DockerContainer().destroy(ref) if __name__ == '__main__': asyncio.run(main()) The finally removes the container even when setup or the run fails. To keep it, store backend.ref instead. DockerContainer’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=[DockerContainer(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. Without an image, the first run builds one from DESKTOP_DOCKERFILE, with Firefox, and later runs reuse it. That image doesn’t get security updates. To update it, build it yourself and pass it as image; under durable execution, do this before the first run, so the build doesn’t count against a step’s timeout: Terminalpython -c "from pydantic_ai_harness.docker_container import DESKTOP_DOCKERFILE; print(DESKTOP_DOCKERFILE)" | docker build --pull --no-cache --tag my-desktop - Then pass DockerContainer(image='my-desktop', desktop=True). Another custom image needs the display’s programs, which the first use installs if it can. 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 Remove a container, with its anonymous volumes, with the ref you stored. A container that is already gone returns quietly: from pydantic_ai.workspaces import WorkspaceRef from pydantic_ai_harness.docker_container import DockerContainer async def remove_container(ref: WorkspaceRef) -> None: await DockerContainer().destroy(ref) DockerContainer() without an image only attaches to and removes containers by ref. A failed run returns no result, so remove its container 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.docker_container import DockerContainer hooks = Hooks() @hooks.on.run_error async def remove_failed_run_container(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 remove short, bounded so a hung call can't hang it. with anyio.move_on_after(30, shield=True): await DockerContainer().destroy(ctx.workspace.ref) raise error agent = Agent('anthropic:claude-opus-5-5', capabilities=[DockerContainer(image='python:3.13-slim'), Coder(), hooks]) Find a lost container If your program stops before it stores the ref, for example after a crash, Ctrl-C or a cancelled run, the container is left behind. To find it, run docker ps --all --filter label=ai.pydantic.workspace=true. It lists every container DockerContainer created. Then remove it: await DockerContainer().destroy(WorkspaceRef(provider='docker', id='<name>')). Work on a project directory Mount a directory on your machine with docker_args, extra docker run arguments: from pathlib import Path from pydantic_ai_harness.docker_container import DockerContainer project = Path('.').resolve() container = DockerContainer( image='python:3.13-slim', docker_args=['--volume', f'{project}:/workspace', '--memory', '2g', '--cpus', '2'], allow_internet_access=False, ) The mount is the only part of your machine’s files the commands can change. For a network of your own, leave allow_internet_access on and pass --network in docker_args. Docker refuses a second --network next to --network none. With desktop, don’t put the container on the host’s network (such as --network host). Programs in it could reach an X server on your machine through Linux’s abstract socket and control your screen. docker_args can’t change the container’s name, label or entrypoint. A new container gets --pids-limit 2048, so a runaway fork loop can’t exhaust the process table of the machine running Docker. A command that hits the limit fails with Cannot fork or Resource temporarily unavailable. Pass your own --pids-limit in docker_args, or -1 to remove it. Use Podman or a remote Docker host Pass executable='podman' to use Podman. The capability uses whichever daemon your docker CLI points at. To run containers on another host, point the CLI there before the agent starts: Terminalexport DOCKER_HOST=ssh://dev@build-box # or: docker context use build-box The host needs Docker, and ssh must log in without a prompt, through a key or your SSH agent. DOCKER_HOST overrides DOCKER_CONTEXT, which overrides docker context use. Unset the ones you don’t us