返回 Skills
pydantic/skills· MIT 内容可用

pydantic-ai-harness

Extend Pydantic AI agents with batteries-included capabilities from pydantic-ai-harness -- Code Mode (collapse many tool calls into one sandboxed Python execution), a filesystem and shell, sub-agents, planning, context compaction, and more. Use when the user mentions pydantic-ai-harness, CodeMode, Monty, code mode, or tool sandboxing, when they want first-party filesystem/shell/sub-agent/planning/compaction capabilities for a Pydantic AI agent, when they want an agent to run agent-written Python, or when a Pydantic AI agent would benefit from orchestrating multiple tool calls in a single sandboxed script.

安装

与 skills.sh 相同的 Command / Prompt 安装方式


name: pydantic-ai-harness description: Extend Pydantic AI agents with batteries-included capabilities from pydantic-ai-harness -- Code Mode (collapse many tool calls into one sandboxed Python execution), a filesystem and shell, sub-agents, planning, context compaction, and more. Use when the user mentions pydantic-ai-harness, CodeMode, Monty, code mode, or tool sandboxing, when they want first-party filesystem/shell/sub-agent/planning/compaction capabilities for a Pydantic AI agent, when they want an agent to run agent-written Python, or when a Pydantic AI agent would benefit from orchestrating multiple tool calls in a single sandboxed script. license: MIT compatibility: Requires Python 3.10+ and pydantic-ai-slim>=2.1.0 metadata: version: "0.1.0" author: pydantic

Building with Pydantic AI Harness

Pydantic AI Harness is the official capability library for Pydantic AI. Capabilities that need model or framework support -- and those fundamental to every agent -- live in core pydantic-ai; optional, batteries-included capabilities live here. Both are composed onto an agent through the same capabilities=[...] API.

This skill covers the capabilities shipped by pydantic-ai-harness. For the core framework -- agents, tools, structured output, hooks, and testing -- use the building-pydantic-ai-agents skill instead.

When to Use This Skill

Invoke this skill when:

  • The user mentions pydantic-ai-harness, CodeMode, code mode, or the Monty sandbox
  • An agent makes many sequential tool calls that could collapse into one sandboxed Python execution
  • The user wants the model to write Python that loops, branches, aggregates, or parallelizes tool calls with asyncio.gather
  • The user asks to sandbox or constrain the code an agent runs

Do not use this skill for:

  • Core Pydantic AI usage -- building agents, adding tools, structured output, streaming, or testing (use building-pydantic-ai-agents)
  • Capabilities that ship in core pydantic-ai, such as web search, tool search, and thinking
  • The Pydantic validation library on its own (pydantic/BaseModel without agents)

Supported Capabilities

CodeMode has a full reference below; it is the flagship capability and the one this skill goes deep on. The rest ship today and each has its own README with API and examples.

Each capability lives in its own submodule and is imported from there (from pydantic_ai_harness.<module> import ...). Capabilities are not importable from the top-level pydantic_ai_harness package by design, so each one keeps its own optional dependencies isolated. CodeMode, FileSystem, Shell, and ManagedPrompt also have top-level re-exports (importable directly from pydantic_ai_harness).

APIs are subject to change between releases; breaking changes ship deprecation warnings where practical.

CapabilityModuleDescription
CodeModepydantic_ai_harness.code_mode (also top-level)Wraps eligible tools into a single sandboxed run_code tool so the model orchestrates them in Python -- see Code Mode
FileSystempydantic_ai_harness.filesystem (also top-level)Read, write, edit, and search files under a root directory, with traversal prevention
Shellpydantic_ai_harness.shell (also top-level)Run commands in a subprocess with allowlists, a default denylist, timeouts, and env masking
ManagedPromptpydantic_ai_harness.logfire (also top-level)Back an agent's instructions with a Logfire-managed prompt
SubAgentspydantic_ai_harness.subagentsDelegate subtasks to specialized child agents
DynamicWorkflowpydantic_ai_harness.dynamic_workflowOrchestrate sub-agents from a model-written Python script
Planningpydantic_ai_harness.planningBreak complex tasks into structured plans before execution
compaction family (SlidingWindow, SummarizingCompaction, ...)pydantic_ai_harness.compactionTrim or summarize conversation history to stay within token limits
OverflowingToolOutputpydantic_ai_harness.overflowing_tool_outputTruncate, summarize, or spill large tool outputs
RepoContextpydantic_ai_harness.contextAuto-load CLAUDE.md/AGENTS.md and repo structure
StepPersistencepydantic_ai_harness.step_persistenceSave, restore, resume, and fork run state
PyaiDocspydantic_ai_harness.docsOn-demand read_pyai_docs tool for Pydantic AI docs
RuntimeAuthoringpydantic_ai_harness.runtime_authoringLet an agent author, validate, and load real capabilities at runtime
media externalizationpydantic_ai_harness.mediaOffload large BinaryContent to content-addressed stores

Still experimental: an ACP server adapter, imported from pydantic_ai_harness.experimental.acp. Importing it emits a HarnessExperimentalWarning.

The full, current list with links and status is in the capability matrix.

Install

uv add pydantic-ai-harness

Each capability declares its own extra. Code Mode needs the Monty sandbox:

uv add "pydantic-ai-harness[codemode]"   # `code-mode` is also accepted as an alias

Requires Python 3.10+ and pydantic-ai-slim>=2.1.0.

Quick Start

A harness capability is added to the agent like any other. Here CodeMode wraps locally registered tools into a single run_code tool that the model drives with Python.

from pydantic_ai import Agent

from pydantic_ai_harness import CodeMode

agent = Agent('anthropic:claude-sonnet-4-6', capabilities=[CodeMode()])


@agent.tool_plain
def get_temperature_f(city: str) -> float:
    return {'Paris': 68.0, 'Tokyo': 77.0}[city]


@agent.tool_plain
def convert_temp(fahrenheit: float) -> float:
    return round((fahrenheit - 32) * 5 / 9, 1)

result = agent.run_sync(
    'Compare the weather in Paris and Tokyo, and report both temperatures in Celsius.'
)
print(result.output)
#> Paris is 20.0 C and Tokyo is 25.0 C.

The model writes a single Python script that fetches both temperatures with asyncio.gather and then converts them -- performing four tool calls across two dependent stages in one run_code invocation.

Key Practices

  • Confirm a harness capability is actually needed. If core Pydantic AI tools and capabilities are enough, use the building-pydantic-ai-agents skill instead -- don't reach for the harness by default.
  • Read the reference before writing code. Each capability has its own configuration, constraints, and gotchas -- load the linked reference (e.g. Code Mode) first.
  • Install the capability's extra. Importing CodeMode without pydantic-ai-harness[codemode] raises an ImportError; the Monty sandbox is an optional dependency.

Common Gotchas

  • native=True tools bypass CodeMode. Provider-native MCP servers and web search execute server-side, so run_code never sees them. Use native=False for client-side dispatch that CodeMode can wrap, but do not treat a remote server as trusted or sandboxed; see the Code Mode trust boundary.
  • The Monty sandbox is a Python subset. No class definitions, no third-party imports, and only a small stdlib allowlist -- read Code Mode before debugging generated code that fails to run.
  • CodeMode needs its extra. Install pydantic-ai-harness[codemode], not the bare package.

附带文件

references/CODE-MODE.md
# Code Mode

`CodeMode` wraps eligible tools into a single `run_code` tool so the model can write Python that loops,
branches, aggregates, and parallelizes multiple tool calls inside a sandbox.

Use it when the agent needs to call several tools, transform intermediate results, run concurrent
tool work with `asyncio.gather`, or anywhere a simple Python script is more reliable than the model alone, such as for mathematics.

## Install

Code Mode needs the Monty sandbox, pulled in by the `codemode` extra:

```bash
uv add "pydantic-ai-harness[codemode]"   # `code-mode` is also accepted as an alias
```

## Basic Pattern

```python {test="skip"}
from pydantic_ai import Agent

from pydantic_ai_harness import CodeMode

agent = Agent('anthropic:claude-sonnet-4-6', capabilities=[CodeMode()])


@agent.tool_plain
def get_weather(city: str) -> dict:
    return {'city': city, 'temp_f': 72, 'condition': 'sunny'}


@agent.tool_plain
def convert_temp(fahrenheit: float) -> float:
    return round((fahrenheit - 32) * 5 / 9, 1)
```

The model could generate code like:

```python {test="skip" lint="skip"}
import asyncio

paris, tokyo = await asyncio.gather(
    get_weather(city='Paris'),
    get_weather(city='Tokyo'),
)
paris_c = await convert_temp(fahrenheit=paris['temp_f'])
tokyo_c = await convert_temp(fahrenheit=tokyo['temp_f'])
{'paris': paris_c, 'tokyo': tokyo_c}
```

This performs four tool calls, across two dependent stages, inside one `run_code` invocation.

## Choose Which Tools Are Sandboxed

The `tools` parameter controls which tools move behind `run_code`.

```python
from pydantic_ai_harness import CodeMode

CodeMode(tools='all')
CodeMode(tools=['search', 'fetch'])
CodeMode(tools=lambda ctx, td: td.name in {'search', 'fetch'})
CodeMode(tools={'code_mode': True})
```

Metadata-based selection is useful when the project already groups tools into toolsets:

```python {test="skip" lint="skip"}
from pydantic_ai import Agent
from pydantic_ai.toolsets import FunctionToolset
from pydantic_ai_harness import CodeMode

search_tools = FunctionToolset(tools=[search, fetch]).with_metadata(code_mode=True)

agent = Agent(
    'anthropic:claude-sonnet-4-6',
    toolsets=[search_tools],
    capabilities=[CodeMode(tools={'code_mode': True})],
)
```

Non-matching tools remain regular tool calls.

## Return Values

`run_code` captures the last expression automatically.

| Scenario | Return |
| --- | --- |
| No print output | Last expression value |
| With print output | `{"output": "<printed text>", "result": <last expression>}` |
| Multimodal content | Returned natively for model processing |

If the user expects a raw dict or list back, avoid unnecessary `print()` statements.

## Retries

```python
from pydantic_ai_harness import CodeMode

CodeMode(
    tools='all',
    max_retries=3,
)
```

Use `max_retries` when sandbox execution errors are expected to be recoverable.
If the generated code fails during sandbox execution, the error message is sent back to the model, and it is asked to redraft the code in light of that failure. This process is repeated up to `max_retries` times, or until the code executes successfully.

## REPL State

State persists between `run_code` calls during the same agent run. Imports, variables, and helper
functions carry over until the run ends. Use `restart: true` in the tool call to reset state when the
conversation has drifted or stale state is causing wrong behavior.

## Sandbox Restrictions

Code runs inside Monty, an implementation of Python which intentionally supports only a subset of features.

Key restrictions:

- No class definitions
- No third-party imports
- No `import *`
- Only a small stdlib subset is allowed: `sys`, `typing`, `asyncio`, `math`, `json`, `re`, `datetime`, `os`, `pathlib`
- No wall-clock or timing primitives by default: `datetime.datetime.now()` and `datetime.date.today()` require an `os_access` handler; `asyncio.sleep` and the `time` module are unavailable
- Filesystem I/O requires an `os_access` handler or a `mount`; `os.getenv` and `os.environ` require an `os_access` handler
- Tools requiring approval or with deferred (`CallDeferred`) execution are sandboxed like any other tool; without a `HandleDeferredToolCalls` (or equivalent) capability to resolve them inline, calling one from `run_code` raises an error that surfaces to the model as a retry

Leave `os_access` and `mount` unset unless the task requires host access, and grant only the resources
the task needs. A mount defaults to copy-on-write `mode='overlay'`; use `mode='read-only'` to forbid
writes or `mode='read-write'` only when sandbox writes must persist on the host.

The sandbox constrains the model-generated Python, not the implementation of the tools it calls.
Wrapped tools retain their normal host and network access, so expose only tools with the authority and
input validation appropriate for model-generated calls.

When a generated example keeps failing, check these restrictions before changing the rest of the agent.

## API

```python {test="skip" lint="skip"}
CodeMode(
    tools: ToolSelector = 'all',           # 'all', list[str], callable, or dict
    max_retries: int = 3,                  # retries on sandbox execution errors
    *,
    os_access: CodeModeOS | None = None,   # host handler for env vars, clock, and file I/O
    mount: CodeModeMount | None = None,    # host directories to share with the sandbox
    dynamic_catalog: bool = False,         # move the tool catalog into dynamic instructions
)
```

## Agent Specs

When the user defines the agent in YAML or JSON, the loader needs to know how to build `CodeMode`:

```yaml
model: anthropic:claude-sonnet-4-6
capabilities:
  - CodeMode: {}
```

```python {test="skip"}
from pydantic_ai import Agent

from pydantic_ai_harness import CodeMode

agent = Agent.from_file('agent.yaml', custom_capability_types=[CodeMode])
```

The same pattern applies when passing arguments:

```yaml
capabilities:
  - CodeMode:
      tools: ['search', 'fetch']
      max_retries: 5
```

## Observability

With Logfire or another OpenTelemetry backend, nested tool calls inside `run_code` produce child spans.
That makes CodeMode much easier to debug than a plain blob of generated code.

```python {test="skip" lint="skip"}
for msg in result.all_messages():
    for part in msg.parts:
        if isinstance(part, ToolReturnPart) and part.tool_name == 'run_code':
            tool_calls = part.metadata['tool_calls']    # dict[str, ToolCallPart]
            tool_returns = part.metadata['tool_returns'] # dict[str, ToolReturnPart]
```