Files
openai--openai-agents-python/examples/sandbox/extensions/daytona/usaspending_text2sql/sql_capability.py
T
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

176 lines
6.1 KiB
Python

from __future__ import annotations
import textwrap
from typing import Any, Literal
from agents.sandbox import Capability, ExecTimeoutError, Manifest
from agents.sandbox.session.base_sandbox_session import BaseSandboxSession
from agents.tool import FunctionTool
# Python script executed inside the sandbox to run SQL queries safely.
# Receives the query on stdin, enforces read-only mode and row limits.
_QUERY_RUNNER_SCRIPT = r"""
import csv, json, os, sqlite3, sys, time
db_path = sys.argv[1]
display_limit = int(sys.argv[2])
csv_limit = int(sys.argv[3])
results_dir = sys.argv[4] if len(sys.argv) > 4 else ""
query = sys.stdin.read().strip()
if not query:
print("Error: empty query")
sys.exit(0)
# Statement-level validation: only allow read-only operations
first_token = query.lstrip().split()[0].upper() if query.strip() else ""
if first_token not in ("SELECT", "WITH", "EXPLAIN", "PRAGMA"):
print(f"Error: only SELECT, WITH, EXPLAIN, and PRAGMA statements are allowed (got {first_token})")
sys.exit(0)
try:
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
conn.execute("PRAGMA query_only = ON")
cursor = conn.execute(query)
columns = [desc[0] for desc in cursor.description] if cursor.description else []
rows = cursor.fetchmany(csv_limit + 1)
conn.close()
except sqlite3.Error as e:
print(f"SQL error: {e}")
sys.exit(0)
if not columns:
print(json.dumps({"columns": [], "rows": [], "row_count": 0, "truncated": False}))
sys.exit(0)
csv_truncated = len(rows) > csv_limit
if csv_truncated:
rows = rows[:csv_limit]
# Save full result as CSV for download
csv_file = ""
if results_dir:
os.makedirs(results_dir, exist_ok=True)
csv_file = f"query_{int(time.time())}_{os.getpid()}.csv"
with open(os.path.join(results_dir, csv_file), "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(columns)
writer.writerows(rows)
# Return only display_limit rows to the model, but report total counts
total_rows = len(rows)
display_rows = rows[:display_limit]
result = {
"columns": columns,
"rows": display_rows,
"row_count": total_rows,
"display_count": len(display_rows),
"truncated": csv_truncated,
}
if csv_file:
result["csv_file"] = csv_file
if total_rows > len(display_rows):
result["note"] = f"Showing {len(display_rows)} of {total_rows} rows. Full result saved to CSV."
print(json.dumps(result))
"""
def _shell_quote(s: str) -> str:
"""Single-quote a string for safe shell interpolation."""
return "'" + s.replace("'", "'\\''") + "'"
_SQL_CAPABILITY_INSTRUCTIONS = textwrap.dedent(
"""\
When querying the database:
- Always use `run_sql` to execute SQL. Never run sqlite3 directly via a shell.
- Write standard SQLite-compatible SQL.
- Prefer aggregations (GROUP BY, SUM, COUNT, AVG) over returning many raw rows.
- The display shows up to 100 rows, but up to 10,000 rows are saved to a downloadable CSV.
If the user needs a large export, let them know the full result is available via the download link.
- Use the schema documentation files in schema/tables/ if you need column details.
- Read schema/glossary.md for official definitions of USAspending terms.
- For monetary values, the database stores amounts in dollars as REAL values.
"""
).strip()
def _make_run_sql_tool(
session: BaseSandboxSession,
db_path: str,
max_display_rows: int,
max_csv_rows: int,
timeout_seconds: float,
results_dir: str,
) -> FunctionTool:
"""Build a FunctionTool that executes read-only SQL inside the sandbox."""
async def run_sql(query: str, limit: int | None = None) -> str:
"""Execute a read-only SQL query against the NASA USAspending SQLite database.
Returns results as JSON with columns, rows, row_count, and truncated fields.
Results are also saved as a downloadable CSV. The display is limited to a
small number of rows, but the CSV may contain many more.
Args:
query: SQL SELECT query to execute against the USAspending database.
Only read-only queries are allowed.
limit: Optional display row limit override.
"""
display_limit = max(1, min(limit or max_display_rows, max_display_rows))
command = (
f"printf '%s' {_shell_quote(query)} "
f"| python3 -c {_shell_quote(_QUERY_RUNNER_SCRIPT)} "
f"{_shell_quote(db_path)} {display_limit} {max_csv_rows}"
f" {_shell_quote(results_dir)}"
)
try:
result = await session.exec(command, timeout=timeout_seconds)
except (ExecTimeoutError, TimeoutError):
return f"Query timed out after {timeout_seconds}s. Try a simpler query or add a LIMIT."
output = result.stdout.decode("utf-8", errors="replace")
stderr = result.stderr.decode("utf-8", errors="replace")
if not result.ok():
return f"Execution error (exit {result.exit_code}):\n{stderr or output}"
return output.strip() if output.strip() else "Query returned no results."
from agents.tool import function_tool as _function_tool
return _function_tool(run_sql, name_override="run_sql")
class SqlCapability(Capability):
type: Literal["sql"] = "sql"
db_path: str = "data/usaspending.db"
max_display_rows: int = 100
max_csv_rows: int = 10_000
timeout_seconds: float = 30.0
results_dir: str = "results"
def bind(self, session: BaseSandboxSession) -> None:
self.session = session
def tools(self) -> list[Any]:
if self.session is None:
raise ValueError("SqlCapability is not bound to a SandboxSession")
return [
_make_run_sql_tool(
session=self.session,
db_path=self.db_path,
max_display_rows=self.max_display_rows,
max_csv_rows=self.max_csv_rows,
timeout_seconds=self.timeout_seconds,
results_dir=self.results_dir,
)
]
async def instructions(self, manifest: Manifest) -> str | None:
return _SQL_CAPABILITY_INSTRUCTIONS