|
| 1 | +""" |
| 2 | +Minimal Sprites-backed sandbox example for manual validation. |
| 3 | +
|
| 4 | +This example creates a small in-memory workspace, lets the agent inspect it |
| 5 | +through one shell tool, and prints a short answer. By default an ephemeral |
| 6 | +sprite is created and deleted at the end; pass ``--sprite-name <name>`` to |
| 7 | +attach to an existing sprite instead. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import argparse |
| 13 | +import asyncio |
| 14 | +import io |
| 15 | +import os |
| 16 | +import sys |
| 17 | +import tempfile |
| 18 | +from pathlib import Path |
| 19 | +from typing import cast |
| 20 | + |
| 21 | +from openai.types.responses import ResponseTextDeltaEvent |
| 22 | + |
| 23 | +from agents import ModelSettings, Runner |
| 24 | +from agents.run import RunConfig |
| 25 | +from agents.sandbox import LocalSnapshotSpec, Manifest, SandboxAgent, SandboxRunConfig |
| 26 | +from agents.sandbox.session import BaseSandboxSession |
| 27 | + |
| 28 | +if __package__ is None or __package__ == "": |
| 29 | + sys.path.insert(0, str(Path(__file__).resolve().parents[3])) |
| 30 | + |
| 31 | +from examples.sandbox.misc.example_support import text_manifest # noqa: E402 |
| 32 | +from examples.sandbox.misc.workspace_shell import WorkspaceShellCapability # noqa: E402 |
| 33 | + |
| 34 | +try: |
| 35 | + from agents.extensions.sandbox import ( |
| 36 | + SpritesSandboxClient, |
| 37 | + SpritesSandboxClientOptions, |
| 38 | + ) |
| 39 | +except Exception as exc: # pragma: no cover - import path depends on optional extras |
| 40 | + raise SystemExit( |
| 41 | + "Sprites sandbox examples require the optional repo extra.\n" |
| 42 | + "Install it with: uv sync --extra sprites" |
| 43 | + ) from exc |
| 44 | + |
| 45 | + |
| 46 | +DEFAULT_QUESTION = "Summarize this sandbox workspace in 2 sentences." |
| 47 | +SNAPSHOT_CHECK_PATH = Path("snapshot-check.txt") |
| 48 | +SNAPSHOT_CHECK_CONTENT = "sprites snapshot round-trip ok\n" |
| 49 | + |
| 50 | + |
| 51 | +def _build_manifest() -> Manifest: |
| 52 | + return text_manifest( |
| 53 | + { |
| 54 | + "README.md": ( |
| 55 | + "# Sprites Demo Workspace\n\n" |
| 56 | + "This workspace exists to validate the Sprites sandbox backend manually.\n" |
| 57 | + ), |
| 58 | + "handoff.md": ( |
| 59 | + "# Handoff\n\n" |
| 60 | + "- Customer: Northwind Traders.\n" |
| 61 | + "- Goal: validate Sprites sandbox exec and persistence flows.\n" |
| 62 | + "- Current status: v1 backend slice (exec + fs + PTY) is wired and under test.\n" |
| 63 | + ), |
| 64 | + "todo.md": ( |
| 65 | + "# Todo\n\n" |
| 66 | + "1. Inspect the workspace files.\n" |
| 67 | + "2. Summarize the current status in two sentences.\n" |
| 68 | + ), |
| 69 | + } |
| 70 | + ) |
| 71 | + |
| 72 | + |
| 73 | +def _require_env(name: str) -> None: |
| 74 | + if os.environ.get(name): |
| 75 | + return |
| 76 | + raise SystemExit(f"{name} must be set before running this example.") |
| 77 | + |
| 78 | + |
| 79 | +async def _read_text(session: BaseSandboxSession, path: Path) -> str: |
| 80 | + data = await session.read(path) |
| 81 | + text = cast(str | bytes, data.read()) |
| 82 | + if isinstance(text, bytes): |
| 83 | + return text.decode("utf-8") |
| 84 | + return text |
| 85 | + |
| 86 | + |
| 87 | +async def _verify_stop_resume(*, sprite_name: str | None) -> None: |
| 88 | + """Round-trip a workspace through tar persistence and reattach. |
| 89 | +
|
| 90 | + With ``sprite_name=None`` an ephemeral sprite is created, persisted, and |
| 91 | + then resumed against itself. With a named sprite the same flow runs |
| 92 | + against the existing sprite (no create/delete on the API). |
| 93 | + """ |
| 94 | + |
| 95 | + client = SpritesSandboxClient() |
| 96 | + options = SpritesSandboxClientOptions(sprite_name=sprite_name) |
| 97 | + |
| 98 | + with tempfile.TemporaryDirectory(prefix="sprites-snapshot-example-") as snapshot_dir: |
| 99 | + sandbox = await client.create( |
| 100 | + manifest=_build_manifest(), |
| 101 | + snapshot=LocalSnapshotSpec(base_path=Path(snapshot_dir)), |
| 102 | + options=options, |
| 103 | + ) |
| 104 | + |
| 105 | + try: |
| 106 | + await sandbox.start() |
| 107 | + await sandbox.write( |
| 108 | + SNAPSHOT_CHECK_PATH, |
| 109 | + io.BytesIO(SNAPSHOT_CHECK_CONTENT.encode("utf-8")), |
| 110 | + ) |
| 111 | + await sandbox.stop() |
| 112 | + finally: |
| 113 | + await sandbox.shutdown() |
| 114 | + |
| 115 | + resumed = await client.resume(sandbox.state) |
| 116 | + try: |
| 117 | + await resumed.start() |
| 118 | + restored = await _read_text(resumed, SNAPSHOT_CHECK_PATH) |
| 119 | + if restored != SNAPSHOT_CHECK_CONTENT: |
| 120 | + raise RuntimeError( |
| 121 | + f"Snapshot resume verification failed: expected " |
| 122 | + f"{SNAPSHOT_CHECK_CONTENT!r}, got {restored!r}" |
| 123 | + ) |
| 124 | + finally: |
| 125 | + await resumed.aclose() |
| 126 | + if sprite_name is None: |
| 127 | + # Ephemeral sandbox should clean up the sprite created by ``resume``. |
| 128 | + await client.delete(resumed) |
| 129 | + |
| 130 | + print("snapshot round-trip ok") |
| 131 | + |
| 132 | + |
| 133 | +async def main( |
| 134 | + *, |
| 135 | + model: str, |
| 136 | + question: str, |
| 137 | + sprite_name: str | None, |
| 138 | + skip_snapshot_check: bool, |
| 139 | + stream: bool, |
| 140 | +) -> None: |
| 141 | + _require_env("OPENAI_API_KEY") |
| 142 | + _require_env("SPRITES_API_TOKEN") |
| 143 | + |
| 144 | + if not skip_snapshot_check: |
| 145 | + await _verify_stop_resume(sprite_name=sprite_name) |
| 146 | + |
| 147 | + manifest = _build_manifest() |
| 148 | + agent = SandboxAgent( |
| 149 | + name="Sprites Sandbox Assistant", |
| 150 | + model=model, |
| 151 | + instructions=( |
| 152 | + "Answer questions about the sandbox workspace. Inspect the files before answering " |
| 153 | + "and keep the response concise. Cite the file names you inspected." |
| 154 | + ), |
| 155 | + default_manifest=manifest, |
| 156 | + capabilities=[WorkspaceShellCapability()], |
| 157 | + model_settings=ModelSettings(tool_choice="required"), |
| 158 | + ) |
| 159 | + |
| 160 | + client = SpritesSandboxClient() |
| 161 | + sandbox = await client.create( |
| 162 | + manifest=manifest, |
| 163 | + options=SpritesSandboxClientOptions(sprite_name=sprite_name), |
| 164 | + ) |
| 165 | + |
| 166 | + run_config = RunConfig( |
| 167 | + sandbox=SandboxRunConfig(session=sandbox), |
| 168 | + tracing_disabled=True, |
| 169 | + workflow_name="Sprites sandbox example", |
| 170 | + ) |
| 171 | + |
| 172 | + try: |
| 173 | + async with sandbox: |
| 174 | + if not stream: |
| 175 | + result = await Runner.run(agent, question, run_config=run_config) |
| 176 | + print(result.final_output) |
| 177 | + return |
| 178 | + |
| 179 | + stream_result = Runner.run_streamed(agent, question, run_config=run_config) |
| 180 | + saw_text_delta = False |
| 181 | + async for event in stream_result.stream_events(): |
| 182 | + if event.type == "raw_response_event" and isinstance( |
| 183 | + event.data, ResponseTextDeltaEvent |
| 184 | + ): |
| 185 | + if not saw_text_delta: |
| 186 | + print("assistant> ", end="", flush=True) |
| 187 | + saw_text_delta = True |
| 188 | + print(event.data.delta, end="", flush=True) |
| 189 | + |
| 190 | + if saw_text_delta: |
| 191 | + print() |
| 192 | + finally: |
| 193 | + await client.delete(sandbox) |
| 194 | + |
| 195 | + |
| 196 | +if __name__ == "__main__": |
| 197 | + parser = argparse.ArgumentParser() |
| 198 | + parser.add_argument("--model", default="gpt-5.5", help="Model name to use.") |
| 199 | + parser.add_argument("--question", default=DEFAULT_QUESTION, help="Prompt to send to the agent.") |
| 200 | + parser.add_argument( |
| 201 | + "--sprite-name", |
| 202 | + default=None, |
| 203 | + help=( |
| 204 | + "Existing sprite to attach to. When omitted, an ephemeral sprite is " |
| 205 | + "created and deleted automatically." |
| 206 | + ), |
| 207 | + ) |
| 208 | + parser.add_argument( |
| 209 | + "--skip-snapshot-check", |
| 210 | + action="store_true", |
| 211 | + default=False, |
| 212 | + help="Skip the tar workspace persistence verification before the agent run.", |
| 213 | + ) |
| 214 | + parser.add_argument("--stream", action="store_true", default=False, help="Stream the response.") |
| 215 | + args = parser.parse_args() |
| 216 | + |
| 217 | + asyncio.run( |
| 218 | + main( |
| 219 | + model=args.model, |
| 220 | + question=args.question, |
| 221 | + sprite_name=args.sprite_name, |
| 222 | + skip_snapshot_check=args.skip_snapshot_check, |
| 223 | + stream=args.stream, |
| 224 | + ) |
| 225 | + ) |
0 commit comments