2d665c9a67
### Sandbox Agents This release adds **Sandbox Agents**, a beta SDK surface for running agents with a persistent, isolated workspace. Sandbox agents keep the normal `Agent` and `Runner` flow, but add workspace manifests, sandbox-native capabilities, sandbox clients, snapshots, and resume support so agents can work over real files, run commands, edit repositories, generate artifacts, and continue work across runs. Key pieces: - `SandboxAgent`: an `Agent` with sandbox defaults such as `default_manifest`, sandbox instructions, capabilities, and `run_as`. - `Manifest`: a fresh-workspace contract for files, directories, local files, local directories, Git repos, environment, users, groups, and mounts. - `SandboxRunConfig`: per-run sandbox wiring for client creation, live session injection, serialized session resume, manifest overrides, snapshots, and materialization concurrency limits. - Built-in capabilities for shell access, filesystem editing and image inspection, skills, memory, and compaction. - Workspace snapshots and serialized sandbox session state for reconnecting to existing work or seeding a fresh sandbox from saved contents. ### Sandbox clients and hosted providers Sandbox agents now support local, containerized, and hosted execution backends: - `UnixLocalSandboxClient` for fast local development. - `DockerSandboxClient` for container isolation and image parity. - Hosted sandbox clients for Blaxel, Cloudflare, Daytona, E2B, Modal, Runloop, and Vercel through optional extras. The release also adds provider-specific examples and mount strategies for common storage backends, including S3, Cloudflare R2, Google Cloud Storage, Azure Blob Storage, and S3 Files where supported by the selected backend. ### Sandbox memory Adds a sandbox memory capability that lets future sandbox-agent runs learn from prior runs. Memory stores extracted lessons in the sandbox workspace, injects a concise summary into later runs, and uses progressive disclosure so agents can search deeper rollout summaries only when useful. Memory supports: - Read-only or generate-only modes. - Live updates when the agent discovers stale memory. - Multi-turn grouping through `conversation_id`, SDK `Session`, `RunConfig.group_id`, or generated run IDs. - Separate memory layouts for isolating memory across agents or workflows. - S3-backed examples for persisted memory across runs. ### Workspace mounts, snapshots, and resume This release adds a full workspace entry and mount model for sandbox sessions: - Local files and directories. - Synthetic files and directories. - Git repository entries. - Remote storage mounts for S3, R2, GCS, Azure Blob Storage, and S3 Files. - Provider-specific mount strategies across Docker, Modal, Cloudflare, Blaxel, Daytona, E2B, and Runloop. - Portable snapshots with path normalization, symlink preservation, mount-safe snapshotting, and remote snapshot support. - Resume paths through runner-managed `RunState`, explicit `SandboxSessionState`, or saved snapshots. ### Examples and tutorials Adds a large `examples/sandbox/` suite covering: - Local Unix and Docker sandbox runners. - Docker mount smoke tests for S3, GCS, Azure Blob Storage, and S3 Files. - Sandbox coding tasks with skills. - Sandbox agents as tools and handoff patterns. - Memory examples, including multi-agent/multi-turn memory and S3-backed memory. - Tax-prep and healthcare-support workflows. - Dataroom QA and metric extraction tutorials. - Repository code review tutorial. - Vision website clone tutorial. - Provider examples for Blaxel, Cloudflare, Daytona, E2B, Modal, Runloop, Temporal, and Vercel. ### Runtime, tracing, and model plumbing The release includes the runtime plumbing needed to make sandbox agents work naturally inside the existing SDK: - Runner-managed sandbox preparation, capability binding, session lifecycle, state serialization, and resume behavior. - Sandbox-aware `RunState` serialization. - Unified sandbox tracing with SDK spans. - Token usage on tracing spans. - Runner-managed prompt cache key defaults. - OpenAI agent registration and harness ID configuration. - Safer redaction of sensitive MCP tool outputs when sensitive tracing is disabled. - Additional OpenAI client/model utilities and Chat Completions coverage. ## Documentation & Other Changes - docs: add Asqav to external tracing processors list. - docs: update translated document pages. Co-authored-by: Abdulrahman Alfozan <alfozan@openai.com> Co-authored-by: Aditya Singh <60082699+adityasingh2400@users.noreply.github.com> Co-authored-by: Andi Liu <andi@openai.com> Co-authored-by: Aron <263346377+aron-cf@users.noreply.github.com> Co-authored-by: ashwinnathan-openai <ashwinnathan@openai.com> Co-authored-by: Codex <noreply@openai.com> Co-authored-by: cploujoux <cploujoux@blaxel.ai> Co-authored-by: elainegan-openai <168589666+elainegan-openai@users.noreply.github.com> Co-authored-by: Elias Freider <freider@users.noreply.github.com> Co-authored-by: Erik Dunteman <erik@erikds-macbook-air.local> Co-authored-by: Jason Liu <jasonliu@openai.com> Co-authored-by: Jason Steving <32336750+jasonsteving99@users.noreply.github.com> Co-authored-by: Kazuhiro Sera <seratch@openai.com> Co-authored-by: Lovre Pešut <lovre.pesut@gmail.com> Co-authored-by: Lucas Wang <lucas_wang@lucas-futures.com> Co-authored-by: Matt Brockman <matt.brockman@e2b.dev> Co-authored-by: Mish Ushakov <mishushakov@users.noreply.github.com> Co-authored-by: Naresh <ghostwriternr@gmail.com> Co-authored-by: nicholasclark-openai <nicholasclark@openai.com> Co-authored-by: qiyaoq-oai <qiyaoq@openai.com> Co-authored-by: Scott Trinh <scott@scotttrinh.com> Co-authored-by: tode-rl <tony@runloop.ai> Co-authored-by: Wendy Jiao <wendyjiao@openai.com>
242 lines
8.5 KiB
Python
242 lines
8.5 KiB
Python
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import sys
|
|
from pathlib import Path
|
|
from typing import Any, Literal, cast
|
|
|
|
from openai.types.responses import ResponseTextDeltaEvent
|
|
|
|
from agents import ModelSettings, Runner
|
|
from agents.run import RunConfig
|
|
from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig
|
|
from agents.sandbox.config import DEFAULT_PYTHON_SANDBOX_IMAGE
|
|
from agents.sandbox.entries import File
|
|
|
|
if __package__ is None or __package__ == "":
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
|
|
|
from examples.sandbox.misc.workspace_shell import WorkspaceShellCapability
|
|
|
|
Backend = Literal["docker", "modal"]
|
|
WorkspacePersistenceMode = Literal["tar", "snapshot_filesystem", "snapshot_directory"]
|
|
|
|
DEFAULT_QUESTION = "Summarize this sandbox project in 2 sentences."
|
|
DEFAULT_BACKEND: Backend = "docker"
|
|
DEFAULT_MODAL_APP_NAME = "openai-agents-python-sandbox-example"
|
|
DEFAULT_MODAL_WORKSPACE_PERSISTENCE: WorkspacePersistenceMode = "tar"
|
|
|
|
|
|
def _stream_event_banner(event_name: str) -> str | None:
|
|
if event_name == "tool_called":
|
|
return "[tool call] shell"
|
|
if event_name == "tool_output":
|
|
return "[tool output] shell"
|
|
return None
|
|
|
|
|
|
def _build_manifest(backend: Backend) -> Manifest:
|
|
backend_label = "Docker" if backend == "docker" else "Modal"
|
|
return Manifest(
|
|
entries={
|
|
"README.md": File(
|
|
content=(
|
|
b"# Demo Project\n\n"
|
|
+ (
|
|
f"This sandbox contains a tiny demo project for the {backend_label} "
|
|
"sandbox runner.\n"
|
|
).encode()
|
|
+ b"The goal is to show how Runner can prepare a sandbox workspace.\n"
|
|
)
|
|
),
|
|
"src/app.py": File(
|
|
content=b'def greet(name: str) -> str:\n return f"Hello, {name}!"\n'
|
|
),
|
|
"docs/notes.md": File(
|
|
content=(
|
|
b"# Notes\n\n"
|
|
b"- The example is intentionally minimal.\n"
|
|
b"- The model should inspect files through the shell tool.\n"
|
|
)
|
|
),
|
|
}
|
|
)
|
|
|
|
|
|
def _build_agent(*, model: str, manifest: Manifest, backend: Backend) -> SandboxAgent:
|
|
backend_label = "Docker" if backend == "docker" else "Modal"
|
|
return SandboxAgent(
|
|
name=f"{backend_label} Sandbox Assistant",
|
|
model=model,
|
|
instructions=(
|
|
"Answer questions about the sandbox workspace. Inspect the project before answering, "
|
|
"and keep the response concise. "
|
|
"Do not guess file names like package.json or pyproject.toml. "
|
|
"This demo intentionally contains a tiny workspace."
|
|
),
|
|
# `default_manifest` tells the sandbox agent which workspace it should expect.
|
|
default_manifest=manifest,
|
|
# `WorkspaceShellCapability()` exposes one shell tool so the model can inspect files.
|
|
capabilities=[WorkspaceShellCapability()],
|
|
# `tool_choice="required"` makes the demo more deterministic by forcing the model
|
|
# to look at the workspace instead of answering from prior assumptions.
|
|
model_settings=ModelSettings(tool_choice="required"),
|
|
)
|
|
|
|
|
|
def _require_modal_dependency() -> tuple[Any, Any]:
|
|
try:
|
|
from agents.extensions.sandbox import ModalSandboxClient, ModalSandboxClientOptions
|
|
except Exception as exc: # pragma: no cover - import path depends on optional extras
|
|
raise SystemExit(
|
|
"Modal-backed runs require the optional repo extra.\n"
|
|
"Install it with: uv sync --extra modal"
|
|
) from exc
|
|
|
|
return ModalSandboxClient, ModalSandboxClientOptions
|
|
|
|
|
|
def _path_resolves_to(path: str, target: Path) -> bool:
|
|
try:
|
|
return Path(path or ".").resolve() == target
|
|
except OSError:
|
|
return False
|
|
|
|
|
|
def _import_docker_from_env() -> Any:
|
|
script_dir = Path(__file__).resolve().parent
|
|
original_sys_path = sys.path[:]
|
|
try:
|
|
sys.path = [entry for entry in sys.path if not _path_resolves_to(entry, script_dir)]
|
|
from docker import from_env as docker_from_env # type: ignore[import-untyped]
|
|
except Exception as exc: # pragma: no cover - import path depends on local Docker setup
|
|
raise SystemExit(
|
|
f"Docker-backed runs failed to import the Docker SDK: {exc}\n"
|
|
"Install the repo dependencies with: make sync\n"
|
|
"If you are running this file directly, try:\n"
|
|
"uv run python -m examples.sandbox.basic --backend docker"
|
|
) from exc
|
|
finally:
|
|
sys.path = original_sys_path
|
|
|
|
return docker_from_env
|
|
|
|
|
|
def _require_docker_dependency() -> tuple[Any, Any, Any]:
|
|
docker_from_env = _import_docker_from_env()
|
|
from agents.sandbox.sandboxes.docker import DockerSandboxClient, DockerSandboxClientOptions
|
|
|
|
return docker_from_env, DockerSandboxClient, DockerSandboxClientOptions
|
|
|
|
|
|
async def _create_session(
|
|
*,
|
|
backend: Backend,
|
|
manifest: Manifest,
|
|
agent: SandboxAgent,
|
|
):
|
|
if backend == "docker":
|
|
docker_from_env, DockerSandboxClient, DockerSandboxClientOptions = (
|
|
_require_docker_dependency()
|
|
)
|
|
client = DockerSandboxClient(docker_from_env())
|
|
sandbox = await client.create(
|
|
manifest=manifest,
|
|
options=DockerSandboxClientOptions(image=DEFAULT_PYTHON_SANDBOX_IMAGE),
|
|
)
|
|
return client, sandbox
|
|
|
|
ModalSandboxClient, ModalSandboxClientOptions = _require_modal_dependency()
|
|
client = ModalSandboxClient()
|
|
sandbox = await client.create(
|
|
manifest=manifest,
|
|
options=ModalSandboxClientOptions(
|
|
app_name=DEFAULT_MODAL_APP_NAME,
|
|
workspace_persistence=DEFAULT_MODAL_WORKSPACE_PERSISTENCE,
|
|
),
|
|
)
|
|
return client, sandbox
|
|
|
|
|
|
async def main(
|
|
model: str,
|
|
question: str,
|
|
backend: Backend,
|
|
) -> None:
|
|
manifest = _build_manifest(backend)
|
|
agent = _build_agent(model=model, manifest=manifest, backend=backend)
|
|
client, sandbox = await _create_session(
|
|
backend=backend,
|
|
manifest=manifest,
|
|
agent=agent,
|
|
)
|
|
|
|
await sandbox.start()
|
|
print(await sandbox.ls("."))
|
|
|
|
try:
|
|
# `async with sandbox` keeps the example on the public session lifecycle API.
|
|
# `Runner` reuses the already-running session without starting it a second time.
|
|
async with sandbox:
|
|
# `Runner.run_streamed()` drives the model and yields text and tool events in real time.
|
|
result = Runner.run_streamed(
|
|
agent,
|
|
question,
|
|
run_config=RunConfig(
|
|
sandbox=SandboxRunConfig(session=sandbox),
|
|
workflow_name=f"{backend.title()} sandbox example",
|
|
),
|
|
)
|
|
saw_text_delta = False
|
|
saw_any_text = False
|
|
|
|
# The stream contains raw text deltas from the assistant plus structured tool events.
|
|
async for event in result.stream_events():
|
|
if event.type == "raw_response_event" and isinstance(
|
|
event.data, ResponseTextDeltaEvent
|
|
):
|
|
if not saw_text_delta:
|
|
print("assistant> ", end="", flush=True)
|
|
saw_text_delta = True
|
|
print(event.data.delta, end="", flush=True)
|
|
saw_any_text = True
|
|
continue
|
|
|
|
if event.type != "run_item_stream_event":
|
|
continue
|
|
|
|
banner = _stream_event_banner(event.name)
|
|
if banner is not None:
|
|
if saw_text_delta:
|
|
print()
|
|
saw_text_delta = False
|
|
print(banner)
|
|
|
|
if saw_text_delta:
|
|
print()
|
|
if not saw_any_text:
|
|
print(result.final_output)
|
|
finally:
|
|
await client.delete(sandbox)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--model", default="gpt-5.4", help="Model name to use.")
|
|
parser.add_argument("--question", default=DEFAULT_QUESTION, help="Prompt to send to the agent.")
|
|
parser.add_argument(
|
|
"--backend",
|
|
default=DEFAULT_BACKEND,
|
|
choices=["docker", "modal"],
|
|
help="Sandbox backend to use for this example.",
|
|
)
|
|
args = parser.parse_args()
|
|
asyncio.run(
|
|
main(
|
|
args.model,
|
|
args.question,
|
|
cast(Backend, args.backend),
|
|
)
|
|
)
|