Index of every page on this site: llms.txt
All skills
pydantic avatar

/building-pydantic-ai-agents

@b2d64a3
by pydanticpydantic/pydantic-ai21k stars
3,221
Run it yourself

Build AI agents with Pydantic AI — tools, capabilities (including on-demand loading), workspaces, structured output, streaming, testing, and multi-agent patterns. Use when the user mentions Pydantic AI, imports pydantic_ai, or asks to build an AI agent, add tools/capabilities, attach a workspace, defer capability loading, stream output, define agents from YAML, or test agent behavior.

Use this Skill: https://skilld.dev/gh/pydantic/pydantic-ai/building-pydantic-ai-agents

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesWORKSPACES.md

≈2.8k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Workspaces

Attach a workspace capability to the agent and use ctx.workspace in tools:

from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities import LocalWorkspace

agent = Agent('openai:gpt-5.2', capabilities=[LocalWorkspace('~/project')])


@agent.tool
async def execute(ctx: RunContext[None], command: list[str]) -> str:
    result = await ctx.workspace.run(command, timeout=30)
    return result.stdout

LocalWorkspace(working_dir, *, read_only=False, authority='operator', path_authority=None, env=None) runs host subprocesses and provides no isolation: working_dir is only the default directory and the base for relative paths, not a jail or a security boundary. Use it only for trusted work. working_dir is required; a relative path such as '.' resolves against the current directory at construction, and a leading ~ is expanded; the caller owns that directory. Commands inherit only PATH, HOME, and the locale variables LANG, LC_ALL, and LC_CTYPE from the agent process, with env and then the per-call env layered on top. Never pass os.environ wholesale: it hands the model's commands every secret in the process, LLM API keys included. read_only=True wraps it in ReadOnlyWorkspace, and authority='user' or 'none' (or any path_authority) in AuthorityWorkspace, for files the operator didn't write (a user's upload, a cloned repo). Two LocalWorkspaces share the default id local_workspace and combine into the last one (none of the earlier one's settings carry over); give one a distinct id to keep both. Its ref is WorkspaceRef(provider='local', id=<absolute working_dir>) from construction (the directory is not checked then; the first operation raises WorkspaceUnavailableError if it is missing), and the capability claims only that exact ref: a foreign ref, or a local ref for another directory, gets None, so message history cannot redirect the agent to another host directory (pass workspace='new' to start over in the configured one). For a single run, pass the backend instead: agent.run(..., workspace=LocalWorkspaceBackend('.')), or workspace=ReadOnlyWorkspace(Workspace(LocalWorkspaceBackend('.'))) for a read-only run (outside durable execution; see below). LocalWorkspace needs POSIX. On Windows, use WindowsWorkspace(working_dir, ...), with the same parameters and the same lack of isolation. Commands run in PowerShell and inherit only the variables Windows tools need to start (PATH, PATHEXT, SYSTEMROOT, TEMP, USERPROFILE, APPDATA and the like) plus env. Paths are Windows paths: ctx.workspace.platform is 'windows', and ctx.workspace.paths (ntpath) joins them. Its ref is WorkspaceRef(provider='windows', id=<absolute working_dir>), and it claims only that exact ref, as LocalWorkspace does. For a single run, pass workspace=WindowsWorkspaceBackend('.'). Without an attached workspace, operations raise WorkspaceUnavailableError; a capability that needs one checks ctx.workspace.attached in before_run and raises a UserError naming what to attach. Workspace offers the same run and file methods for every backend; WrapperWorkspace is the base for policy wrappers (override operations, delegate the rest to self.wrapped), ReadOnlyWorkspace blocks commands and changes, and workspace.read_only lets a tool provider leave write tools out. AuthorityWorkspace changes no operation: workspace.authority ('operator' | 'user' | 'none', the lowest of any wrappers) is the authority of its files. Set it with AuthorityWorkspace: overriding authority on another wrapper changes neither authority_of nor what outer layers report. path_authority={path: level} (on the wrapper or LocalWorkspace) overrides it per directory or file: the longest matching path wins, relative paths resolve against the working directory, and a path outside it is at 'none' unless listed. await workspace.authority_of(path) gives one file's level, following symlinks and taking the lower of the link's and the target's level. A capability that puts file text it reads from the workspace in instructions asks authority_of per file when it reads it, keeps that level with the text, and sends the text with no more authority (no built-in capability reads it yet). It is not access control: tools still reach every path, and a file read with a tool is tool output whatever its level. To disable workspace access for a run on purpose, pass workspace=UnavailableWorkspace(reason=...): its operations raise WorkspaceUnavailableError with that reason, which a tool can catch as a WorkspaceError.

run(..., cwd=path) starts one command in another existing directory (relative to the working directory) on any backend, by changing into it through sh; a missing one raises FileNotFoundError.

resolve() is textual; realpath() asks the environment to resolve symlinks in the existing components (native through SupportsRealpath, readlink in the shell otherwise). With neither, it only normalizes the text, so a path check built on it cannot see through symlinks.

Outside a durable container, an explicit backend passed through workspace= is used directly, and a Workspace facade or wrapper (ReadOnlyWorkspace(...), result.workspace, ctx.workspace) is kept as-is (inside one, see below). An explicit WorkspaceRef is offered to configured capabilities, and raises if none recognizes it. workspace='new' ignores any ref in message history and asks capabilities with ref=None for a fresh workspace, raising if none supplies one. With workspace=None, capabilities receive the latest ModelResponse.workspace_ref from message history; a latest None suppresses older ones. History supplies identity, not provider configuration. Precedence is: explicit workspace=, then the history ref, then a fresh workspace from the capability. An agent may have several workspace capabilities, like resolve_model_id: they are asked in order and the first that returns a workspace wins (capabilities passed to the run are asked before the agent's), so listing a new provider's capability before the old one moves new conversations while old ones continue where they started. A history ref that no capability recognizes raises UserError (pass workspace='new' to start fresh), unless the agent has no workspace capability at all (a summarizer given the history), which ignores it. With no ref and no supplier the run gets an UnavailableWorkspace whose operations raise WorkspaceUnavailableError explaining how to attach one. get_workspace runs before for_run (a capability that only a for_run contributes is asked afterwards, and for_run may not change a selection made before it), is synchronous, and must have no side effects or I/O. A capability must return None for references it does not own. A workspace capability can't be deferred: defer_loading=True on one raises UserError.

A WorkspaceRef names an environment that exists, and exists only once it does. A backend built without a ref reports ref is None, creates the environment on its first operation, and sets ref as soon as the create call returns; a backend built with a ref attaches on its first operation and raises WorkspaceUnavailableError if the environment is gone, never creating a replacement. A ref is never a label: no name-, conversation- or uuid-derived ref before the environment exists. get_workspace is the only path from a ref back to a workspace. The local backend is the one exception where the ref precedes any operation (the directory is the environment); working_dir() raises WorkspaceUnavailableError if the directory is missing. When a run ends, workspace.ref is recorded as workspace_ref on its last ModelResponse (None if no environment was created). A run without an attached workspace (an agent with no workspace capability, or workspace=UnavailableWorkspace(...)) records the ref from history instead, so the next turn continues in it; after workspace='new' nothing is carried forward.

The core does not create or destroy environments at run boundaries; the application owns SDK retries (outside durable execution), cleanup, TTL and pause/stop through the provider's SDK or run hooks. Workspace.backend reaches the concrete backend for provider-specific methods (not from workflow code under durable execution). Sandbox providers (Modal, E2B, Sprites, Daytona, boxd, Kubernetes agent-sandbox, local smolvm microVMs, local Docker containers, and self-hosted OpenSandbox servers), SSHWorkspace for a remote host, and BubblewrappedWorkspace for confining another workspace's commands to its working directory ship as capabilities in the Pydantic AI Harness. Check a custom backend by subclassing pydantic_ai.workspaces.conformance.WorkspaceBackendSuite and providing its backend fixture.

Exception contract a backend must follow: WorkspaceUnavailableError when the environment is gone or unreachable (ends the run; never reaches the model); WorkspaceTimeoutError for a command over its timeout=; builtin file errors (FileNotFoundError, IsADirectoryError, ...) for path-level failures the model can act on; WorkspaceReadOnlyError for a mutation on a read-only workspace; WorkspaceError for other deliberate refusals; TypeError/ValueError for bad arguments. SDK transient errors propagate unchanged (durable engines retry them); if the SDK cannot tell a dead environment from a failed operation, probe with working_dir() and raise WorkspaceUnavailableError. UserError belongs to the facade and policy wrappers, not backends.

result.workspace continues with a live backend; result.workspace.ref lets another worker attach.

Under TemporalDurability, DBOSDurability or PrefectDurability, attach the workspace capability at agent construction and nothing else is needed: in workflow code (hooks, output functions, result.workspace) every Workspace call runs as a durable unit, and inside a unit (a tool) ctx.workspace is the plain workspace, rebuilt on Temporal from the serialized ref through the same capabilities (policy wrappers included). One ensure unit at run start creates or attaches the environment and records its ref and working directory, so all units share one environment and working_dir()/resolve() need no unit. Inside a container workspace= takes None, 'new', a WorkspaceRef, a previous result.workspace, or a live instance whose ref a capability recognizes, which is rebuilt through that capability. A wrapper around it, such as ReadOnlyWorkspace or AuthorityWorkspace, is rejected with UserError unless the capability rebuilds the same policy, so put policy on the capability (e.g. LocalWorkspace(..., read_only=True)). A live instance without a recognized ref raises UserError. Workspace calls retry like capability operations, so a command or write may repeat if a worker dies mid-call. The deprecated TemporalAgent/DBOSAgent/PrefectAgent wrappers refuse workspaces in their container.

See the workspace guide for protocol details and lifecycle examples.

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts1mo3 checks · Risk SAFE
  • Gen Agent Trust Hub1mo

    The skill provides comprehensive guidance for building AI agents using the Pydantic AI framework. It correctly identifies security considerations for powerful features like code execution, file system access, and credential management, providing appropriate warnings and best practices for their safe use.

  • Socket1mo

    No alerts

  • Snyk1mo

    Risk: LOW · No issues

Signed by skilld at b2d64a3. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 3 days ago
compatibility
Requires Python 3.11+
metadata
{
  "version": "1.1.2",
  "author": "pydantic"
}

README badge

README badge for pydantic/pydantic-ai/building-pydantic-ai-agents