openai-agents-python/examples/sandbox/healthcare_support/main.py
Steve Coffey 2d665c9a67
Sandbox Agents (#2889)
### 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>
2026-04-15 10:00:40 -07:00

152 lines
4.6 KiB
Python

from __future__ import annotations
import argparse
import asyncio
import json
import sys
from pathlib import Path
from typing import Any
if __package__ is None or __package__ == "":
_DEMO_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(_DEMO_DIR.parents[2]))
sys.path.insert(0, str(_DEMO_DIR))
from examples.auto_mode import confirm_with_fallback, input_with_fallback # noqa: E402
from examples.sandbox.healthcare_support.data import ( # noqa: E402
HealthcareSupportDataStore,
load_root_env,
)
from examples.sandbox.healthcare_support.models import ScenarioCase # noqa: E402
from examples.sandbox.healthcare_support.tools import HealthcareSupportContext # noqa: E402
from examples.sandbox.healthcare_support.workflow import ( # noqa: E402
CACHE_ROOT,
DEFAULT_SESSION_ID,
SESSION_DB_PATH,
build_context,
run_healthcare_support_workflow,
)
DEFAULT_SCENARIO_ID = "eligibility_verification_basic"
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Run the healthcare support Agents SDK demo from the command line.",
)
parser.add_argument(
"--scenario",
dest="scenario_id",
default=None,
help="Scenario ID to run. If omitted, the CLI asks interactively.",
)
parser.add_argument(
"--list-scenarios",
action="store_true",
help="Print the built-in scenario IDs and exit.",
)
parser.add_argument(
"--reset-memory",
action="store_true",
help="Delete the shared SQLite session database before running.",
)
return parser
def _print_scenarios(store: HealthcareSupportDataStore) -> None:
print("Available scenarios:\n")
for scenario_id in store.list_scenario_ids():
scenario = store.get_scenario(scenario_id)
print(f"- {scenario.scenario_id}")
print(f" {scenario.description}")
def _pick_scenario(store: HealthcareSupportDataStore, requested_id: str | None) -> ScenarioCase:
if requested_id:
return store.get_scenario(requested_id)
scenario_id = input_with_fallback(
"Enter a scenario ID: ",
DEFAULT_SCENARIO_ID,
).strip()
if not scenario_id:
scenario_id = DEFAULT_SCENARIO_ID
return store.get_scenario(scenario_id)
async def _approval_handler(request: dict[str, Any]) -> bool:
print("\nHuman approval requested")
print(f"Agent: {request.get('agent', 'unknown')}")
print(f"Tool: {request.get('tool', 'route_to_human_queue')}")
print(json.dumps(request.get("arguments", {}), indent=2))
return confirm_with_fallback("Approve handoff to a human queue? [y/N]: ", True)
def _print_run_header(*, scenario: ScenarioCase, context: HealthcareSupportContext) -> None:
print("\n" + "=" * 80)
print("Healthcare Support Agents SDK Demo")
print(f"Scenario: {scenario.scenario_id}")
print(f"Description: {scenario.description}")
print(f"SQLite memory session: {context.session_id}")
print("\nCustomer transcript:\n")
print(scenario.transcript)
def _print_run_result(payload: dict[str, Any]) -> None:
print("\nTrace URL:")
print(payload["trace_url"])
print("\nPatient-facing response:\n")
print(payload["resolution"]["patient_facing_response"])
print("\nInternal summary:")
print(payload["resolution"]["internal_summary"])
print("\nNext step:")
print(payload["resolution"]["next_step"])
if payload["resolution"].get("handoff_id"):
print("\nHuman handoff:")
print(payload["resolution"]["handoff_id"])
print("\nGenerated sandbox artifacts:")
for artifact in payload.get("artifacts", []):
print(f"- {artifact['path']}")
print("\nMemory recap:")
print(json.dumps(payload["memory_recap"], indent=2))
print(f"\nSession memory items: {payload['session_memory_items']}")
async def main() -> None:
load_root_env()
args = _build_parser().parse_args()
store = HealthcareSupportDataStore.load()
if args.list_scenarios:
_print_scenarios(store)
return
if args.reset_memory and SESSION_DB_PATH.exists():
SESSION_DB_PATH.unlink()
scenario = _pick_scenario(store, args.scenario_id)
context = build_context(
store=store,
scenario_id=scenario.scenario_id,
session_id=DEFAULT_SESSION_ID,
)
CACHE_ROOT.mkdir(parents=True, exist_ok=True)
_print_run_header(scenario=scenario, context=context)
payload = await run_healthcare_support_workflow(
context=context,
scenario_id=scenario.scenario_id,
approval_handler=_approval_handler,
)
_print_run_result(payload)
if __name__ == "__main__":
asyncio.run(main())