Backends API¶
Async adaptation¶
pydantic_ai_backends.adapter.ensure_async(backend, *, executor=None)
¶
Return an async backend, wrapping sync ones as needed.
An already-async backend is passed through untouched, which is the point: a thread adapter around async code is not merely wasteful but a deadlock waiting to happen, since each call then occupies a worker thread that has to hop back onto the event loop. Two things mark a backend as already async, in this order:
- Subclassing :class:
~pydantic_ai_backends.AsyncBaseSandbox. Unambiguous, and the recommended way to write one. read_bytesbeing a coroutine function. The fallback, for a backend that implements the protocol without inheriting from anything. It has to be a method-shape check rather thanisinstanceagainstAsyncBackendProtocol, because a runtime-checkableProtocolcompares method names — and a sync backend has exactly the same ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
BackendProtocol | AsyncBackendProtocol
|
Sync or async backend. |
required |
executor
|
Executor | None
|
Thread pool for a newly created adapter. Ignored when
|
None
|
Returns:
| Type | Description |
|---|---|
AsyncBackendProtocol
|
An async view of |
Source code in src/pydantic_ai_backends/adapter.py
pydantic_ai_backends.adapter.is_async_backend(backend)
¶
Whether a backend is already asynchronous and must not be thread-wrapped.
Public because it is the contract a third-party backend is judged by, and getting it wrong is expensive in a way that is hard to debug: a natively async backend mistaken for a sync one gets wrapped in a thread adapter, which calls its coroutine function in a worker thread and hands the caller the resulting coroutine object where bytes were expected — no exception, just nonsense.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
object
|
The backend to classify. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Whether the backend implements the async protocol directly. |
Source code in src/pydantic_ai_backends/adapter.py
Base classes¶
Subclass one of these to write your own sandbox: implement execute and edit
and every other file operation is derived from shell commands. See
Writing your own backend for
which one to pick.
pydantic_ai_backends.backends.base.BaseSandbox
¶
Bases: _SandboxIdentity, ABC
Base class for synchronous sandboxes that expose a shell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sandbox_id
|
str | None
|
Unique identifier for this sandbox. Generated when omitted. |
None
|
Source code in src/pydantic_ai_backends/backends/base.py
| Python | |
|---|---|
80 81 82 83 84 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 | |
start()
¶
is_alive()
¶
Whether the sandbox is running and responsive.
Override this. The default answer is "no", and SessionManager reads
it as "replace the sandbox" — so a subclass that never overrides it has a
sandbox built, stopped and rebuilt on every single operation. It defaults
to False rather than True because a sandbox wrongly believed alive is
the harder failure to diagnose, but neither default is right for a real
sandbox: answer it.
Source code in src/pydantic_ai_backends/backends/base.py
stop(purge=False)
¶
Stop and clean up the sandbox.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
purge
|
bool
|
Also discard what the sandbox accumulated — its filesystem, and any workspace kept for it outside the container. Left off, the sandbox ends while its files survive for the next attach; turned on, the thing the sandbox belonged to is gone for good. Accepted by every sandbox so one call site can end any of them, and the subclasses that cannot tell the two apart say so: a Daytona sandbox and a Kubernetes pod are deleted either way, because neither keeps a filesystem this library can reattach to. |
False
|
Source code in src/pydantic_ai_backends/backends/base.py
execute(command, timeout=None)
abstractmethod
¶
Run a command in the sandbox.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
Command to execute. |
required |
timeout
|
int | None
|
Maximum execution time in seconds. |
None
|
Source code in src/pydantic_ai_backends/backends/base.py
edit(path, old_string, new_string, replace_all=False)
abstractmethod
¶
Edit a file by replacing a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path to edit. |
required |
old_string
|
str
|
String to find and replace. |
required |
new_string
|
str
|
Replacement string. |
required |
replace_all
|
bool
|
Replace every occurrence instead of only the first. |
False
|
Source code in src/pydantic_ai_backends/backends/base.py
pydantic_ai_backends.backends.base.AsyncBaseSandbox
¶
Bases: _SandboxIdentity, ABC
Base class for natively asynchronous sandboxes that expose a shell.
Subclass this when the sandbox is reached over an async transport — asyncssh,
an async HTTP client, any async SDK. Implement execute and edit as
coroutines and every other operation is derived from shell commands, exactly
as the synchronous base does.
Subclassing this rather than wrapping async code in a synchronous facade is
not a style preference. ensure_async cannot see through a facade: it
wraps the facade in a thread adapter, so each call runs on a worker thread
that has to hop back onto the event loop to reach the real async code. A
sandbox whose own recovery path also needs a thread — reprovisioning a dead
container, say — then waits for a thread that is waiting for the loop, and
starves the pool for every other agent sharing it. Being async all the way
down means ensure_async passes the backend through untouched and the
toolset awaits it directly.
Recognised by ensure_async through this base class, so no method-shape
sniffing is involved:
from pydantic_ai_backends import AsyncBaseSandbox, ExecuteResponse
class SSHSandbox(AsyncBaseSandbox):
async def execute(self, command: str, timeout: int | None = None) -> ExecuteResponse:
result = await self._connection.run(command, timeout=timeout)
return ExecuteResponse(output=result.stdout, exit_code=result.exit_status)
async def edit(self, path, old_string, new_string, replace_all=False) -> EditResult:
...
Failures are returned, never raised — see
:class:~pydantic_ai_backends.protocol.AsyncBackendProtocol for the contract
every method here is held to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sandbox_id
|
str | None
|
Unique identifier for this sandbox. Generated when omitted. |
None
|
Source code in src/pydantic_ai_backends/backends/base.py
| Python | |
|---|---|
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 | |
start()
async
¶
is_alive()
async
¶
Whether the sandbox is running and responsive.
Override this. The default answer is "no", and SessionManager reads
it as "replace the sandbox" — so a subclass that never overrides it has a
sandbox built, stopped and rebuilt on every single operation. It defaults
to False rather than True because a sandbox wrongly believed alive is
the harder failure to diagnose, but neither default is right for a real
sandbox: answer it.
Source code in src/pydantic_ai_backends/backends/base.py
stop(purge=False)
async
¶
Stop and clean up the sandbox.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
purge
|
bool
|
Also discard what the sandbox accumulated. See
:meth: |
False
|
execute(command, timeout=None)
abstractmethod
async
¶
Run a command in the sandbox.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
Command to execute. |
required |
timeout
|
int | None
|
Maximum execution time in seconds. |
None
|
Source code in src/pydantic_ai_backends/backends/base.py
edit(path, old_string, new_string, replace_all=False)
abstractmethod
async
¶
Edit a file by replacing a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path to edit. |
required |
old_string
|
str
|
String to find and replace. |
required |
new_string
|
str
|
Replacement string. |
required |
replace_all
|
bool
|
Replace every occurrence instead of only the first. |
False
|
Source code in src/pydantic_ai_backends/backends/base.py
LocalBackend¶
pydantic_ai_backends.backends.local.LocalBackend
¶
Local filesystem backend with optional shell execution.
File operations are native Python; execute shells out. Both are confined
to allowed_directories, and can be narrowed further with a permission
ruleset.
Example
Source code in src/pydantic_ai_backends/backends/local.py
| Python | |
|---|---|
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 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 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 | |
execute_enabled
property
¶
Whether shell execution is enabled.
__init__(root_dir=None, allowed_directories=None, enable_execute=True, sandbox_id=None, permissions=None, ask_callback=None, ask_fallback='error')
¶
Initialize the backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root_dir
|
str | Path | None
|
Base directory for file operations. Defaults to the first allowed directory, or the current working directory. |
None
|
allowed_directories
|
list[str] | None
|
Directories file operations are confined to,
resolved to absolute paths and created when missing. When
omitted, only |
None
|
enable_execute
|
bool
|
Whether shell execution is available. |
True
|
sandbox_id
|
str | None
|
Unique identifier for this backend instance. |
None
|
permissions
|
PermissionRuleset | None
|
Optional ruleset applied after the allowed-directory check passes. |
None
|
ask_callback
|
AskCallback | None
|
Async callback for "ask" actions, receiving
|
None
|
ask_fallback
|
AskFallback
|
What an unanswerable "ask" does — |
'error'
|
Source code in src/pydantic_ai_backends/backends/local.py
ls_info(path)
¶
List one directory, omitting entries denied for "ls".
An "ask" counts as visible, since a listing cannot prompt.
Source code in src/pydantic_ai_backends/backends/local.py
read(path, offset=0, limit=DEFAULT_READ_LIMIT)
¶
Read a slice of a file with line numbers.
Source code in src/pydantic_ai_backends/backends/local.py
write(path, content)
¶
Write a file, creating parent directories as needed.
Source code in src/pydantic_ai_backends/backends/local.py
edit(path, old_string, new_string, replace_all=False)
¶
Edit a file by replacing a string.
Source code in src/pydantic_ai_backends/backends/local.py
glob_info(pattern, path='.')
¶
Match files by glob, most recently modified first.
That ordering matches ripgrep and Claude Code, and is usually what an agent wants; the path breaks ties so the order is stable. Matches denied for "glob" are omitted, and "ask" counts as visible.
Source code in src/pydantic_ai_backends/backends/local.py
grep_raw(pattern, path=None, glob=None, ignore_hidden=True)
¶
Search file contents, using ripgrep when it is installed.
Files denied for "grep" — or for "read", since a match carries content — never contribute results. An explicit "grep" deny on the search path errors the whole search.
Source code in src/pydantic_ai_backends/backends/local.py
execute(command, timeout=None)
¶
Run a shell command in the root directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
Command to execute. |
required |
timeout
|
int | None
|
Maximum execution time in seconds. Defaults to
|
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If execution is disabled for this backend. |
Source code in src/pydantic_ai_backends/backends/local.py
StateBackend¶
pydantic_ai_backends.backends.state.StateBackend
¶
In-memory file storage backend.
Files live in a dictionary and are ephemeral — lost when the process ends,
unless a host persists :attr:files and hands it back. Useful for testing,
for scratch space alongside a real backend, and as the whole storage layer
for an application that keeps the document itself.
Binary content is stored base64 (see :class:~pydantic_ai_backends.FileData)
so that document is always JSON. read and grep decline to treat such a
file as text rather than showing its encoded form; read_bytes returns
exactly what was written.
Example
from pydantic_ai_backends import StateBackend
backend = StateBackend()
backend.write("/src/app.py", "print('hello')")
content = backend.read("/src/app.py")
print(content) # " 1\tprint('hello')"
matches = backend.grep_raw("print")
restored = StateBackend(files=json.loads(json.dumps(backend.files)))
Source code in src/pydantic_ai_backends/backends/state.py
| Python | |
|---|---|
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 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 | |
files
property
¶
The internal files dictionary.
Always a JSON-serialisable document: json.loads(json.dumps(files))
round-trips, and so does storing it in a PostgreSQL jsonb column.
__init__(files=None)
¶
Initialize the backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
files
|
dict[str, FileData] | None
|
Optional initial file dictionary. A document a previous
instance produced, including one that has been through JSON,
loads unchanged — as does one written before |
None
|
Source code in src/pydantic_ai_backends/backends/state.py
ls_info(path)
¶
List the files and directories directly under path.
Source code in src/pydantic_ai_backends/backends/state.py
read(path, offset=0, limit=2000)
¶
Read a slice of a file with line numbers.
A binary file is refused rather than rendered: its stored form is base64, and handing that to a model as if it were the file's text is worse than saying there is nothing here to read.
Source code in src/pydantic_ai_backends/backends/state.py
write(path, content)
¶
Write a file, replacing any existing content.
Source code in src/pydantic_ai_backends/backends/state.py
edit(path, old_string, new_string, replace_all=False)
¶
Edit a file by replacing a string.
Source code in src/pydantic_ai_backends/backends/state.py
glob_info(pattern, path='/')
¶
Match stored paths against a glob pattern.
Source code in src/pydantic_ai_backends/backends/state.py
grep_raw(pattern, path=None, glob=None, ignore_hidden=True)
¶
Search stored file contents for a regex.
Source code in src/pydantic_ai_backends/backends/state.py
CompositeBackend¶
pydantic_ai_backends.backends.composite.CompositeBackend
¶
Backend that routes operations to other backends by path prefix.
Note
Paths reach the matched backend as-is — no prefix is stripped — so
every backend must accept the full virtual path. StateBackend accepts
any path, which makes it the natural choice for a route. LocalBackend
validates paths against its root_dir and will reject virtual paths, so
use it as the default, not inside routes.
Example
from pydantic_ai_backends import CompositeBackend, LocalBackend, StateBackend
backend = CompositeBackend(
default=LocalBackend(root_dir="/home/user/project"),
routes={"/scratch/": StateBackend()},
)
backend.write("src/app.py", "...") # real filesystem
backend.write("/scratch/temp.txt", "...") # ephemeral
Source code in src/pydantic_ai_backends/backends/composite.py
| Python | |
|---|---|
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 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 | |
__init__(default, routes=None)
¶
Initialize the composite.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
BackendProtocol
|
Backend for paths that match no route. |
required |
routes
|
dict[str, BackendProtocol] | None
|
Path prefix to backend, e.g. |
None
|
Source code in src/pydantic_ai_backends/backends/composite.py
ls_info(path)
¶
List one directory, showing route mount points when listing /.
Source code in src/pydantic_ai_backends/backends/composite.py
read(path, offset=0, limit=2000)
¶
write(path, content)
¶
edit(path, old_string, new_string, replace_all=False)
¶
Edit via the backend handling this path.
Source code in src/pydantic_ai_backends/backends/composite.py
glob_info(pattern, path='/')
¶
Match files, searching every backend when starting from the root.
Source code in src/pydantic_ai_backends/backends/composite.py
grep_raw(pattern, path=None, glob=None, ignore_hidden=True)
¶
Search, covering every backend when no specific path is given.
An error from any backend is returned as-is rather than dropped, so a failed search is never mistaken for no matches.