Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions doc/code/framework.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,10 @@ If you are contributing to PyRIT, that work will most likely land in one of the
persists it. Outbound request metadata is separate from chat role, so missing trace
links remain detectable on tool and assistant continuations.
- Because targets are so varied, it is reasonable to return multiple tool calls, or none at all.
- A target that runs tools itself bounds its tool loop. When a tool raises `ToolInfrastructureError`,
such as a `SandboxToolProvider` tool whose sandbox failed, the target answers every pending call and
ends the turn with an error response whose metadata says why (`ToolLoopStop`), rather than asking
the model to fix infrastructure. `OpenAIResponseTarget` does this today.
- One attack can have many targets (and in fact, converters and scorers can also use targets to convert/score the prompt).
- **Does not own**: what to send or what to do with the response. A target sends a prepared `Message` and returns a response — it doesn't convert prompts (converters), score (scorers), manage the conversation or decide the next turn (attacks), apply attack logic, or persist prompts and responses to memory (the `prompt_normalizer` owns that). Its retries stay at the target layer (e.g. `RateLimitException`).

Expand Down Expand Up @@ -304,6 +308,10 @@ If you are contributing to PyRIT, that work will most likely land in one of the
evidence; a sandbox that cannot run it is an acquisition error, so the verdict is undetermined
rather than false.
Each scoring call runs afresh; an observation identifies the run and supports explicit replay.
- `SandboxCheckScorer` runs a fixed check program in the stateful sandbox where a model's tool calls
ran, and scores the judged response by what the check finds. It never runs the response's text, and
never reuses a stored verdict, because the sandbox can change. The caller owns isolation between
attempts, for example by resetting the sandbox.
- Observation lifecycle is optional. A scorer that implements `AttemptObserver`, whether it is a
root scorer or wrapped inside one, is asked by the attack to start observing after setup, once
its attempt ID is allocated and before anything is sent, and to stop when the attempt ends. A
Expand Down Expand Up @@ -382,15 +390,24 @@ The below talks about responsibilities of most modules in the PyRIT library

## Code Execution (Experimental)

**Responsibility**: Connect to caller-configured execution backends and return typed invocation results.
**Responsibility**: Connect to caller-configured execution backends, run programs in them by the same
rules whatever the backend, and return typed invocation results.

- The client API is private and experimental in `pyrit._code_execution`; it may change without a deprecation cycle.
- The API is private and experimental in `pyrit._code_execution`; it may change without a deprecation cycle.
- Targets, converters, dataset generators, and scorers can inject the same `SandboxClient` contract
from `pyrit._code_execution`. Execution inputs and results are private types in `pyrit.models.code_execution`.
- `runtime_profile_name` selects a client-owned configuration by name, not by supplying an image or command.
Clients advertise the available names through `get_runtime_profile_names()`.
- `Sandbox` is the base class for backends. An adapter translates a few hooks into its infrastructure's
API; the base class owns the rules: validation against declared limits, one shared session per
`environment` sandbox (state persists, callers take turns), retries only when nothing ran, renewal,
idle close, cancellation, reset, quarantine and evidence. A `call` sandbox keeps nothing between calls.
`SandboxRegistry` names sandboxes so every caller shares one `Sandbox` object per sandbox.
- A sandbox may keep state between calls, so a program can see what earlier calls left. Runs are
reproducible only in a `call` sandbox, such as the Docker example.
- PyRIT does not own environments. The one-image Docker example is the only exception:
`DockerSandboxClient` manages disposable containers; callers supply the daemon and pinned image.
- `SandboxToolProvider` (in targets) and `SandboxCheckScorer` (in scorers) build on `Sandbox`.
- **Does not own**: interpreting results, scoring criteria, message or seed creation, memory
persistence, or infrastructure setup. Those remain with the consumer or caller.

Expand Down
12 changes: 12 additions & 0 deletions doc/code/scoring/7_program_execution_scorer.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,18 @@
"Real execution and fault coverage is in `tests/integration/score/test_program_execution_scorer_integration.py`.\n",
"Opt in with `RUN_ALL_TESTS=true`; the tests require the daemon and pinned image above."
]
},
{
"cell_type": "markdown",
"id": "7",
"metadata": {},
"source": [
"## Check what a model's code did\n",
"\n",
"`ProgramExecutionScorer` runs the program a response contains. To score a response by what the model's\n",
"code did in a sandbox instead, `SandboxCheckScorer` runs a fixed check program in that sandbox after the\n",
"turn, and never runs the response itself. See [Sandboxed tool calls](../targets/12_sandboxed_tool_calls.md)."
]
}
],
"metadata": {
Expand Down
7 changes: 7 additions & 0 deletions doc/code/scoring/7_program_execution_scorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,10 @@
# %% [markdown]
# Real execution and fault coverage is in `tests/integration/score/test_program_execution_scorer_integration.py`.
# Opt in with `RUN_ALL_TESTS=true`; the tests require the daemon and pinned image above.

# %% [markdown]
# ## Check what a model's code did
#
# `ProgramExecutionScorer` runs the program a response contains. To score a response by what the model's
# code did in a sandbox instead, `SandboxCheckScorer` runs a fixed check program in that sandbox after the
# turn, and never runs the response itself. See [Sandboxed tool calls](../targets/12_sandboxed_tool_calls.md).
185 changes: 185 additions & 0 deletions doc/code/targets/12_sandboxed_tool_calls.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
# Sandboxed Tool Calls

To test a model that acts by running code, its code has to run somewhere isolated that can keep its work
across a conversation, and something other than the model has to say what that code did. PyRIT has three
pieces for this:

- a **`Sandbox`**, which runs programs on some infrastructure, such as a container, a VM or a hosted service;
- **`SandboxToolProvider`**, which turns a sandbox into tools a model can call, such as `run_python`;
- **`SandboxCheckScorer`**, which runs a fixed check program in the same sandbox after a turn and scores the
response by what the check finds.

`pyrit._code_execution` is experimental, and so are the two classes built on it: their API may change
without a deprecation cycle.

## Give a model tools that run in a sandbox

Register each sandbox once, under a name, so that targets, scorers and operators share one `Sandbox`
object, and with it one session. An initializer is a good place to do it. Then give a tool-calling target the
sandbox's tools:

```python
from pyrit._code_execution import SandboxRegistry
from pyrit.prompt_target import OpenAIResponseTarget, SandboxToolProvider

SandboxRegistry.get_registry_singleton().register(MySandbox(...), name="windows-1")

target = OpenAIResponseTarget(
tool_providers=[SandboxToolProvider(sandbox="windows-1")],
max_tool_rounds=20,
)
```

The model sees ordinary tools in its own API:

| Tool | What it does |
|------|--------------|
| `run_<runtime>` | Runs a program once, such as `run_python` or `run_powershell`, with optional arguments, standard input and timeout |
| `write_file`, `read_file`, `list_dir` | Work with files, in sandboxes whose files persist between calls |

Results are JSON. `run_<runtime>` returns the exit code, the output of each stream (cut at
`max_output_chars`, and marked when cut), whether the program timed out, and how long it took. A program
that fails is an ordinary result the model can read and fix.

Arguments are checked against the sandbox's limits before anything runs, so a call rejected there goes back to
the model as an error, with the reason, and is never recorded as invoked. When the sandbox itself fails, the
tool raises `ToolInfrastructureError`, and `OpenAIResponseTarget` ends the turn with an error response
instead of asking the model to fix a problem that isn't its own. Every call the model made still gets a
result, so the conversation's history stays valid; the model is told only that the tool's infrastructure
failed, while the error response, which is never replayed to the model, keeps the details. Its `ToolLoopStop`
metadata says why the turn ended. `max_tool_rounds` bounds how many responses with tool calls one send runs;
it defaults to 10.

When a script is done with its sandboxes, close them so no session is left open:

```python
await SandboxRegistry.get_registry_singleton().close_all_async()
```

`close_async` is final. To end a session and keep using the sandbox, use `release_async`, which can also
retry a close that couldn't be confirmed, even after `close_async`.

## Check what the code did

A model's claim that it succeeded is not evidence. A check program, run in the same sandbox after the turn,
verifies the effect itself:

```python
from pyrit.models import Equals, ProgramBehaves, ProgramCase, ProgramResult
from pyrit.score import SandboxCheckScorer

check = SandboxCheckScorer(
sandbox="windows-1",
check_program="import os\nprint('present' if os.path.exists('C:/task.flag') else 'absent')\n",
condition=ProgramBehaves(
runtime_profile_name="windows-python",
cases=(ProgramCase(expected=ProgramResult(stdout=Equals(value="present"))),),
),
)
```

Use it as an attack's objective scorer. It scores the response being judged true when every case of the
check produces its expected result, and false when one doesn't. When the sandbox fails, or the check times
out, the score is undetermined, so an infrastructure problem is never counted as the model failing. The
response's own text never runs. The check's program and output are stored as an observation linked to the
score.

The check reads the sandbox as it is when it runs. So it runs again on every call rather than reusing a
stored verdict, and isolation is the caller's job, since a later attempt could otherwise score true on an
earlier attempt's effect: run one attempt at a time per sandbox (`max_concurrency=1`), turn off automatic
retries of failed attempts (`max_attempts_on_failure=0`), and reset the sandbox between attempts. It needs a
sandbox whose state persists.

The check runs as the same account as the model's code, so it must not trust anything the model could have
written. For example, run Python checks in isolated mode, so a module the model saved in the working
directory can't stand in for a standard one.

## The Docker example

`DockerSandboxClient` runs each program in a disposable, network-less container, so nothing persists
between calls, and it offers `run_<profile>` tools only. It needs a Docker daemon and pre-pulled, pinned
images; [Program execution and scoring](../scoring/7_program_execution_scorer.ipynb) shows how to configure
it. PyRIT includes it as an example of an adapter, not as a hardened sandbox.

```python
from pyrit._code_execution import DockerRuntimeProfile, DockerSandboxClient
from pyrit.prompt_target import OpenAIResponseTarget, SandboxToolProvider

docker = DockerSandboxClient(
profiles={
"python": DockerRuntimeProfile(
image="python@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1",
command=("python3", "-I"),
)
}
)
target = OpenAIResponseTarget(tool_providers=[SandboxToolProvider(sandbox=docker)])
```

## Bring your own sandbox

An adapter is a small `Sandbox` subclass that translates a few calls into an infrastructure's own API.
PyRIT does the rest, so every sandbox behaves the same:

```python
from pyrit._code_execution import ProcessResult, Sandbox, SandboxCapabilities, SandboxStatus


class MySandbox(Sandbox):
def _build_identifier(self): ... # static configuration only, never session ids or secrets
def _get_capabilities(self) -> SandboxCapabilities: ... # runtimes, state kind, limits

async def _execute_async(
self, *, session_id, runtime_profile_name, program, arguments, stdin, timeout_seconds
) -> ProcessResult: ...

async def _open_session_async(self, *, owner) -> str: ... # not needed when nothing persists
async def _close_session_async(self, *, session_id) -> None: ... # closing twice must be safe
async def _get_status_async(self) -> SandboxStatus: ... # optional
async def _reset_async(self, *, expected_revision) -> None: ... # optional; returns when done
```

The capabilities name the runtimes (optionally with a `tool_name`, such as `powershell` for a runtime
called `windows-powershell`), the limits, and the **state kind**, which tells PyRIT whether work persists,
and so how to share the sandbox:

| State kind | Meaning | What PyRIT does |
|------------|---------|-----------------|
| `environment` | State lives in the machine and survives closing a session | One shared session, which callers take turns using |
| `call` | Nothing persists between calls | No sessions; calls run concurrently; no file tools |

Adapters raise these errors, so PyRIT knows what is safe to retry:

| Error | Meaning | What PyRIT does |
|-------|---------|-----------------|
| `SandboxInputError` | The request was invalid, and nothing ran | Reports it to the caller, or to the model |
| `SandboxBusyError` | The sandbox can't start the work right now, and nothing ran | Retries opening a session until the deadline; reports a busy run |
| `SandboxSessionLostError` | The session is gone, and nothing ran | Reopens the session and retries once |
| `SandboxRevisionChangedError` | A reset was refused, because the revision changed | Reports it to the caller |
| anything else | The outcome is unknown | Closes the session and never retries |

For every adapter, PyRIT validates the runtime, the size of the input and the timeout before anything
runs, and reports status, with its own session state, through `get_status_async`. For an `environment`
sandbox, it also:

- opens the session on first use, closes it after ten idle minutes, and renews it before a session time
limit could cut a call short;
- lets one call at a time use the sandbox, first come first served, and waits up to five minutes for a turn;
- when a caller gives up, lets its running program finish, holding the sandbox so nothing runs beside it,
and starts nothing more for it, not even a run that was waiting out a busy sandbox;
- quarantines the sandbox when it can't confirm that a session closed, that a run's processes stopped, or
that a reset finished, until `release_async`, which retries the close, or `reset_async`;
- resets only after the running call finishes, closing the session first, and records the outcome.

A `call` sandbox's calls run in their callers' tasks, so the adapter cleans up when a caller gives up.

`FakeSandbox` is an in-memory sandbox that never runs code. It stands in for a real one when you test code
that uses a sandbox. To check an adapter itself, run the contract-test kit against a live sandbox you can
discard or reset: it writes files, resets the sandbox when it can, and runs real programs to check the
declared limits, error mapping, state, status, reset, and closing twice.

```python
from pyrit._code_execution import SandboxProbes, check_sandbox_contract_async

await check_sandbox_contract_async(sandbox=MySandbox(...), probes=SandboxProbes.python())
```
1 change: 1 addition & 0 deletions doc/myst.yml
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ project:
- file: code/targets/10_2_playwright_target_copilot.ipynb
- file: code/targets/10_3_websocket_copilot_target.ipynb
- file: code/targets/11_message_normalizer.ipynb
- file: code/targets/12_sandboxed_tool_calls.md
- file: code/targets/hack_a_prompt_target.ipynb
- file: code/targets/open_ai_completions.ipynb
- file: code/targets/github_copilot_target.ipynb
Expand Down
46 changes: 45 additions & 1 deletion pyrit/_code_execution/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,58 @@
from pyrit.common.lazy_imports import get_lazy_dir, resolve_lazy_export

if TYPE_CHECKING:
from pyrit._code_execution.client import SandboxClient, SandboxExecutionError
from pyrit._code_execution.client import (
SandboxBusyError,
SandboxClient,
SandboxExecutionError,
SandboxInputError,
SandboxRevisionChangedError,
SandboxSessionLostError,
SandboxUnavailableError,
)
from pyrit._code_execution.docker_client import DockerRuntimeProfile, DockerSandboxClient
from pyrit._code_execution.fake_sandbox import FakeRun, FakeSandbox, FakeSandboxHook
from pyrit._code_execution.sandbox import (
ProcessResult,
RuntimeProfile,
Sandbox,
SandboxCapabilities,
SandboxCondition,
SandboxResetRecord,
SandboxStateKind,
SandboxStatus,
SandboxView,
)
from pyrit._code_execution.sandbox_contract import SandboxContractError, SandboxProbes, check_sandbox_contract_async
from pyrit._code_execution.sandbox_registry import SandboxRegistry, resolve_sandbox

_LAZY_EXPORTS: dict[str, str] = {
"SandboxClient": "pyrit._code_execution.client",
"SandboxExecutionError": "pyrit._code_execution.client",
"SandboxInputError": "pyrit._code_execution.client",
"SandboxBusyError": "pyrit._code_execution.client",
"SandboxSessionLostError": "pyrit._code_execution.client",
"SandboxRevisionChangedError": "pyrit._code_execution.client",
"SandboxUnavailableError": "pyrit._code_execution.client",
"DockerRuntimeProfile": "pyrit._code_execution.docker_client",
"DockerSandboxClient": "pyrit._code_execution.docker_client",
"FakeRun": "pyrit._code_execution.fake_sandbox",
"FakeSandbox": "pyrit._code_execution.fake_sandbox",
"FakeSandboxHook": "pyrit._code_execution.fake_sandbox",
"ProcessResult": "pyrit._code_execution.sandbox",
"RuntimeProfile": "pyrit._code_execution.sandbox",
"Sandbox": "pyrit._code_execution.sandbox",
"SandboxCapabilities": "pyrit._code_execution.sandbox",
"SandboxCondition": "pyrit._code_execution.sandbox",
"SandboxResetRecord": "pyrit._code_execution.sandbox",
"SandboxStateKind": "pyrit._code_execution.sandbox",
"SandboxStatus": "pyrit._code_execution.sandbox",
"SandboxView": "pyrit._code_execution.sandbox",
"SandboxContractError": "pyrit._code_execution.sandbox_contract",
"SandboxProbes": "pyrit._code_execution.sandbox_contract",
"check_sandbox_contract_async": "pyrit._code_execution.sandbox_contract",
"SandboxRegistry": "pyrit._code_execution.sandbox_registry",
"resolve_sandbox": "pyrit._code_execution.sandbox_registry",
}

__all__ = list(_LAZY_EXPORTS)
Expand Down
Loading
Loading