Docker API¶
DockerSandbox¶
The container DockerWorkspace runs on. Use it directly to manage containers
yourself; it runs commands through the CommandRunner
protocol and has no file operations of its own — reach files through a workspace.
pydantic_ai_backends.backends.docker.sandbox.DockerSandbox
¶
One Docker container: its lifecycle, its limits, and commands run in it.
The container starts lazily on the first command or an explicit
:meth:start. Commands go through :meth:run_command, which keeps the
workspace contract; files are reached through those commands by whoever uses
the container — :class:~pydantic_ai_backends.workspaces.DockerWorkspace, or
sandboxd, which also mounts the work directory from the host.
Example
Source code in src/pydantic_ai_backends/backends/docker/sandbox.py
| Python | |
|---|---|
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 | |
runtime
property
¶
The runtime configuration for this sandbox.
id
property
¶
Unique identifier for this sandbox.
session_id
property
¶
Alias for the sandbox id, used for session management.
work_dir
property
¶
Directory commands start in and relative paths resolve against.
__init__(image='python:3.12-slim', sandbox_id=None, work_dir='/workspace', auto_remove=True, runtime=None, session_id=None, idle_timeout=3600, volumes=None, network_mode=None, container_name=None, mem_limit=None, memswap_limit=None, cpus=None, cpu_shares=None, pids_limit=DEFAULT_PIDS_LIMIT, tmpfs=None, oci_runtime=None, reattach_only=False)
¶
Initialize the sandbox without starting its container.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
str
|
Docker image to use. Ignored when |
'python:3.12-slim'
|
sandbox_id
|
str | None
|
Unique identifier for this sandbox. |
None
|
work_dir
|
str
|
Working directory inside the container. Ignored when
|
'/workspace'
|
auto_remove
|
bool
|
Remove the container when it stops. Forced to |
True
|
runtime
|
RuntimeConfig | str | None
|
|
None
|
session_id
|
str | None
|
Alias for |
None
|
idle_timeout
|
int
|
Idle seconds after which |
3600
|
volumes
|
dict[str, str] | None
|
Host-to-container mounts, as |
None
|
network_mode
|
str | None
|
Docker network mode ( |
None
|
container_name
|
str | None
|
Stable name to reattach to across restarts, which
preserves installed packages and other filesystem state.
Implies |
None
|
mem_limit
|
str | None
|
Memory ceiling in Docker syntax ( |
None
|
memswap_limit
|
str | None
|
Ceiling on memory and swap combined, in the same
syntax. It is the wrong default on a host backed by |
None
|
cpus
|
float | None
|
Hard CPU ceiling in cores, e.g. |
None
|
cpu_shares
|
int | None
|
Relative CPU weight (Docker's default is 1024). Unlike
|
None
|
pids_limit
|
int | None
|
Maximum number of processes. |
DEFAULT_PIDS_LIMIT
|
tmpfs
|
dict[str, str] | None
|
In-memory mounts, as Its pages count against |
None
|
oci_runtime
|
str | None
|
Low-level runtime the daemon starts this container
with — Docker's This is the one knob that changes the isolation boundary
rather than a resource ceiling, which is why it is per sandbox:
The runtime must already be registered with the daemon in
|
None
|
reattach_only
|
bool
|
Start the container named |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/pydantic_ai_backends/backends/docker/sandbox.py
| Python | |
|---|---|
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | |
start()
¶
stop(purge=False, *, remove=None)
¶
Stop the container.
A container created without container_name runs with
auto_remove=True and is discarded by the daemon on exit. A named
container deliberately survives, since reuse across restarts is the
whole point of naming it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
purge
|
bool
|
Also remove the container, discarding its filesystem state.
Named |
False
|
remove
|
bool | None
|
The old name for |
None
|
Source code in src/pydantic_ai_backends/backends/docker/sandbox.py
is_alive()
¶
Whether the container is running.
The answer is cached for ALIVE_CACHE_SECONDS, since reload() is a
daemon round trip and session managers call this on every request.
Source code in src/pydantic_ai_backends/backends/docker/sandbox.py
resource_usage()
¶
Sample the container's current resource usage.
One non-streaming stats() call, which costs a daemon round trip and
should be polled sparingly rather than per request.
Source code in src/pydantic_ai_backends/backends/docker/sandbox.py
run_command(argv, *, run_id, env=None, timeout=None, output_limit=None)
async
¶
Run argv under the workspace failure contract.
Raises when the container is unreachable, keeps stdout and stderr apart,
and stops the command's process group when the caller times out or is
cancelled. It is what a Pydantic AI workspace and sandboxd's /run are
built on.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
Sequence[str]
|
The program and its arguments, passed through literally. |
required |
run_id
|
str
|
Names the run so :meth: |
required |
env
|
Mapping[str, str] | None
|
Variables layered over the container's environment. |
None
|
timeout
|
float | None
|
Seconds before the command is stopped; none when |
None
|
output_limit
|
int | None
|
Combined output bytes before the command is stopped;
the module default when |
None
|
Raises:
| Type | Description |
|---|---|
SandboxUnavailableError
|
The container is gone or not running. |
Source code in src/pydantic_ai_backends/backends/docker/sandbox.py
stop_command(run_id)
async
¶
Stop a command :meth:run_command started, and everything it started.
Does nothing when the run has already finished or never started here.
Source code in src/pydantic_ai_backends/backends/docker/sandbox.py
SessionManager¶
pydantic_ai_backends.backends.docker.session.SessionManager
¶
Creates, reuses and reaps one sandbox per session id.
Example
Source code in src/pydantic_ai_backends/backends/docker/session.py
| Python | |
|---|---|
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 | |
sessions
property
¶
Copy of the active sessions.
session_count
property
¶
Number of active sessions.
__init__(sandbox_factory=None, default_runtime=None, default_idle_timeout=3600, workspace_root=None, max_sessions=None, on_release=None, executor=None, in_use=None)
¶
Initialize the manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sandbox_factory
|
SandboxFactory | None
|
Builds a sandbox for a session id. It must offer
|
None
|
default_runtime
|
RuntimeConfig | str | None
|
Runtime for new Docker sandboxes. Only used on the default path. |
None
|
default_idle_timeout
|
int
|
Idle seconds before a session may be reaped, for sandboxes that do not carry their own timeout. |
3600
|
workspace_root
|
str | Path | None
|
Root for persistent session storage. Only used on
the default path, where |
None
|
max_sessions
|
int | None
|
Ceiling on simultaneously open sessions. Once reached,
:meth: |
None
|
on_release
|
Callable[[str], None] | None
|
Called with a session id just after its sandbox is
stopped, by :meth: |
None
|
executor
|
Executor | None
|
Thread pool the blocking |
None
|
in_use
|
Callable[[str], bool] | None
|
Whether a session has an operation under way, for a caller that tracks them. Idle cleanup never stops such a session: its last activity is when the operation began, and a command longer than the idle timeout is not idle. |
None
|
Source code in src/pydantic_ai_backends/backends/docker/session.py
get_or_create(session_id, runtime=None)
async
¶
Return the session's live sandbox, creating one when needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
Unique identifier for the session. |
required |
runtime
|
RuntimeConfig | str | None
|
Runtime to use. Only applies on the default Docker path. |
None
|
Cancelling the caller does not cancel a start under way. A sandbox's
start is a call on a worker thread that keeps going regardless, so a
start abandoned half-way used to leave a running container no session
named. The start finishes and the sandbox is registered like any other,
for release or idle cleanup to stop; shutdown waits for it.
Raises:
| Type | Description |
|---|---|
SessionLimitExceeded
|
If |
Source code in src/pydantic_ai_backends/backends/docker/session.py
release(session_id)
async
¶
Stop a session's sandbox. Returns whether the session existed.
Takes the session's lock, so a release cannot land in the middle of a
get_or_create for the same id. Without it the two interleaved: the
release removed the entry get_or_create was about to delete (a
KeyError out of a public coroutine) and removed the lock it was
holding, after which a third caller interned a new lock and created a
second sandbox for one session — the leak the lock is meant to prevent.
Source code in src/pydantic_ai_backends/backends/docker/session.py
cleanup_idle(max_idle=None)
async
¶
Stop the sandboxes that have been idle too long.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_idle
|
int | None
|
Idle ceiling in seconds applied to every session,
overriding each sandbox's own. When omitted, a sandbox's
|
None
|
Returns:
| Type | Description |
|---|---|
int
|
Number of sessions cleaned up. |
Source code in src/pydantic_ai_backends/backends/docker/session.py
start_cleanup_loop(interval=DEFAULT_CLEANUP_INTERVAL)
¶
Reap idle sessions periodically in the background.
The loop survives a failing pass: an unreachable daemon or one uncooperative sandbox is logged and retried on the next tick, because a loop that exits leaves every future container to accumulate unnoticed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
int
|
Seconds between passes. |
DEFAULT_CLEANUP_INTERVAL
|
Source code in src/pydantic_ai_backends/backends/docker/session.py
stop_cleanup_loop()
¶
shutdown()
async
¶
Stop every session and the cleanup loop.
Sessions are stopped concurrently, because stopping one is seconds of waiting for the process inside to die and they do not wait on each other: sequentially, a full pool turned a shutdown into minutes, and an orchestrator that loses patience kills the process mid-teardown.
Returns:
| Type | Description |
|---|---|
int
|
Number of sessions that were stopped. |
Source code in src/pydantic_ai_backends/backends/docker/session.py
RuntimeConfig¶
The runtime descriptor (image, setup commands, environment) used by
DockerSandbox, DockerWorkspace and the session manager is
documented in the type reference: RuntimeConfig.
Built-in Runtimes¶
from pydantic_ai_backends import BUILTIN_RUNTIMES
# Available runtimes
print(sorted(BUILTIN_RUNTIMES))
# Use a runtime
from pydantic_ai_backends import DockerWorkspace
workspace = DockerWorkspace(runtime="python-datascience")
| Runtime | Image | What it adds |
|---|---|---|
python-minimal |
python:3.12-slim | standard library only |
python-datascience |
built on python:3.12-slim | pandas, numpy, matplotlib, scikit-learn, seaborn |
python-analytics |
built on python:3.12-slim | duckdb, polars, pyarrow |
python-web |
built on python:3.12-slim | fastapi, uvicorn, sqlalchemy, httpx |
python-scraping |
built on python:3.12-slim | httpx, beautifulsoup4, lxml, markdownify |
python-documents |
built on python:3.12-slim | pypdf, python-docx, openpyxl, pillow |
node-minimal |
node:24-slim | nothing |
node-typescript |
built on node:24-slim | typescript, tsx, vitest |
node-react |
built on node:24-slim | typescript, vite, react, react-dom, @types/react |
bun |
oven/bun:1-slim | Bun's own bundler, test runner and package manager |
deno |
denoland/deno:alpine | TypeScript with no install step |
go |
golang:1.23-alpine | Go toolchain |
rust |
rust:1-slim | Rust toolchain with cargo |
A runtime naming an image starts as fast as a pull. One naming a base_image
plus packages builds an image on first use and hits the cache afterwards, which
is worth it when installing them per session would dominate.