Examples and guides for using the OpenAI API
Add Databricks Sandbox application-managed example (#3231)
HsingTang8495326b6f1b
diff --git a/authors.yaml b/authors.yamlindex 26b00632..a557fdc7 100644--- a/authors.yaml+++ b/authors.yaml@@ -3,6 +3,11 @@# You can optionally customize how your information shows up cookbook.openai.com over here.# If your information is not present here, it will be pulled from your GitHub profile.+HsingTang:+ name: "Hsing-chih Tang (Databricks)"+ website: "https://linkedin.com/in/hsingchih-tang"+ avatar: "https://avatars.githubusercontent.com/HsingTang"+sperry-openai:name: "David Sperry"website: "https://www.linkedin.com/in/davidrsperry"diff --git a/examples/agents_api/sandboxes/README.md b/examples/agents_api/sandboxes/README.mdindex ed93e9c2..e7d8d14a 100644--- a/examples/agents_api/sandboxes/README.md+++ b/examples/agents_api/sandboxes/README.md@@ -17,6 +17,7 @@ provider compute; each example documents cleanup of both.| --- | --- | --- || [Blaxel](blaxel/README.md) | [Run](blaxel/application_managed/README.md) | [Deploy](blaxel/webhook_managed/README.md) || [Cloudflare](cloudflare/README.md) | [Run](cloudflare/application_managed/README.md) | [Deploy](cloudflare/webhook_managed/README.md) |+| [Databricks](databricks/README.md) | [Run](databricks/application_managed/README.md) | Not included || [Daytona](daytona/README.md) | [Run](daytona/application_managed/README.md) | [Deploy](daytona/webhook_managed/README.md) || [DigitalOcean](digitalocean/README.md) | [Run](digitalocean/application_managed/README.md) | [Deploy](digitalocean/webhook_managed/README.md) || [Docker](docker/README.md) | [Run](docker/application_managed/README.md) | Not included |diff --git a/examples/agents_api/sandboxes/databricks/README.md b/examples/agents_api/sandboxes/databricks/README.mdnew file mode 100644index 00000000..2b92c2bb--- /dev/null+++ b/examples/agents_api/sandboxes/databricks/README.md@@ -0,0 +1,117 @@+# Running OpenAI agents using a Databricks Sandbox++[Databricks Sandbox](https://docs.databricks.com/aws/en/compute/serverless/sandbox) now supports the [OpenAI Agents API](https://developers.openai.com/api/docs/guides/agents-api/overview), enabling developers to run AI agent code and tool calls in an isolated, serverless environment backed by Databricks' networking and governance controls.++With this integration, OpenAI handles agent orchestration while Databricks Sandbox provides on-demand compute for executing code and interacting with tools and enterprise resources. Developers can control network connectivity and file access, bringing agent execution into an environment designed for enterprise workloads.++In this guide, we'll walk through [application-managed](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle#start-an-environment) sandbox provisioning, where your application uses the Databricks SDK to provision and manage the sandbox lifecycle, from creation and execution to cleanup.++## How it works++Your application is in the driver's seat for the whole session. It creates the agent session, provisions the sandbox, launches the executor, runs the turn, and tears everything down - all through outbound calls (to OpenAI and to the Databricks SDK). Nothing needs to accept an inbound connection, so the application can run anywhere: a laptop, a Databricks job, or a notebook.++The lifecycle:++- Create an agent session with self-hosted environment configuration.+- Provision the sandbox and poll its status to confirm the sandbox is running. The sandbox already has a codex binary built in.+- Launch `codex exec-server` inside the sandbox; it connects outbound to OpenAI and waits for tool calls.+- Submit input and stream the turn; the agent runs shell and file tools in the sandbox.+- Tear down the session and the sandbox.++++## Usage example with Databricks SDK++The agent session is created with the OpenAI client, pointing its `workspace_directory` at a writable path in the sandbox. Your application can use `databricks-sdk` for sandbox lifecycle management and command execution.++`codex exec-server` must stay running on the sandbox for the whole agent session. Your application can launch the process detached using `execute_command_sync`, which lets the command-execution request return while the codex process keeps running on the sandbox.++```py+import os++w = WorkspaceClient(profile="my-workspace")+app_key = os.environ["OPENAI_API_KEY"] # application key+executor_api_key = os.environ["OPENAI_EXECUTOR_API_KEY"] # environment key -> CODEX_API_KEY+++async with AsyncOpenAI(api_key=app_key) as client:+ # Create the self-hosted session first; it returns the environment to connect back to.+ session = await client.beta.agents.sessions.create(+ agent={"model": "gpt-5.6-sol"},+ environment={"type": "self_hosted", "workspace_directory": WORK_DIR},+ )++ # Provision the sandbox via databricks-sdk.+ # Sandboxes typically become ready within sub-seconds.+ sandbox = w.sandbox.create_sandbox(+ Sandbox(+ spec=SandboxSpec(+ compute=ComputeSpec(inactivity_timeout=Duration(seconds=900)))+ ),+ sandbox_id="openai-agent-sandbox",+ )+ name = sandbox.name++ # Launch codex exec-server detached, using the session's environment id/URL.+ remote_url = session.environment.remote_url+ environment_id = session.environment.id+ w.sandbox.execute_command_sync(+ name, "/bin/bash",+ args=["-lc", f"CODEX_HOME=$(mktemp -d) setsid nohup codex exec-server "+ f"--remote {remote_url} --environment-id {environment_id} </dev/null >log 2>&1 & echo pid=$!"],+ envs={"CODEX_API_KEY": executor_api_key},+ )++ # Submit input and stream the turn.+ async with client.beta.agents.sessions.stream(session.id, input=task) as events:+ async for event in events:+ ... # agent runs tools in the sandbox and streams output+```++See the complete, runnable example in the [application-managed example](application_managed/README.md).++## Prerequisites and limits++- An OpenAI application key (`OPENAI_API_KEY`) for creating sessions and submitting input.+- A separate OpenAI executor key (`OPENAI_EXECUTOR_API_KEY`) with the same organization, project, and user or service account as the session. It is passed to codex in the sandbox as `CODEX_API_KEY`.+- If your OpenAI organization enforces an IP allowlist, the sandbox's egress IP must be added to the allowlist; Managed Agents then rejects traffic from unregistered IPs. See [Databricks Outbound IPs](https://docs.databricks.com/aws/en/resources/ip-domain-region#outbound-ips) for the list of Databricks IPs that need to be allowlisted.++## Ending a turn++A turn is finished when the session stream reports the main agent's turn as completed, failed, or cancelled. Read back any results you need from the sandbox with `execute_command_sync`, then clean up the resources: stop the executor, delete the session, and delete the sandbox.++## Stopping and restarting the sandbox between turns++To free compute between turns, stop the sandbox after the turn with `w.sandbox.stop_sandbox(name)` and start it again before the next turn with `w.sandbox.start_sandbox(name)`.++The sandbox's persistent home (`/home/sandbox-agent`) survives stop and start, so any files under this directory are preserved. The `codex exec-server` process is killed when a sandbox stops, and needs to be relaunched after sandbox restart to reconnect to the agent session.++A sandbox can also be configured to auto-stop after it has been idle for `ComputeSpec.inactivity_timeout`. To disable sandbox auto-stop, set `inactivity_timeout` to 0 or leave the field unset.++## Networking++A sandbox has unrestricted outbound egress and closed inbound ingress. Both are currently unconfigurable.++If your OpenAI organization enforces an IP allowlist, add the sandbox's outbound egress IP (see [Databricks Outbound IPs](https://docs.databricks.com/aws/en/resources/ip-domain-region#outbound-ips)). The egress IP is stable while a sandbox is running but can change across stop and restart cycles.++## Monitoring++The executor writes a log inside the sandbox; read it with `execute_command_sync` (tail the exec-server log) to see registration and connection status or errors.++You can examine the state of a sandbox with `w.sandbox.get_sandbox(name).status.state`.++## Troubleshooting++| Symptom | What to check |+| --- | --- |+| Executor rejected with `401 ... IP is not authorized` | The sandbox egress IP is not on your OpenAI organization allowlist (if your org enforces one). Add it, then re-check after a restart - the egress IP can change across stop/restart. |+| Executor rejected with `403 missing required scope api.agents.environments.connect` | The executor is using a general API key. Create a dedicated environment key on the OpenAI Agents tab and pass it as `CODEX_API_KEY`. |+| `codex exec-server` exits right after launch | Tail the executor log in the sandbox. Check the environment id, remote URL, key ownership, and outbound network access. |+| Agent reports that shell or filesystem tools are unavailable | `workspace_directory` does not exist or is not writable. Create it (under `/home/sandbox-agent`) before the turn. |++## Related resources++- [Databricks Sandbox documentation](https://docs.databricks.com/aws/en/compute/serverless/sandbox)+- [Sandbox SDK on databricks-sdk for Python](https://databricks-sdk-py.readthedocs.io/en/latest/workspace/sandbox/sandbox.html)+- [Running commands in sandboxes](https://databricks-sdk-py.readthedocs.io/en/latest/sandbox-command-execution.html)+- [OpenAI Agents API, self-hosted sandboxes](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted)diff --git a/examples/agents_api/sandboxes/databricks/application_managed/README.md b/examples/agents_api/sandboxes/databricks/application_managed/README.mdnew file mode 100644index 00000000..e74e560d--- /dev/null+++ b/examples/agents_api/sandboxes/databricks/application_managed/README.md@@ -0,0 +1,65 @@+# Application-managed Databricks Sandbox++Your application creates an Agents API session and a Databricks sandbox, starts+`codex exec-server` in the sandbox, and runs one turn in which the agent writes a+greeting file. The example reads the file back to verify, then stops the executor,+deletes the session, and deletes the sandbox. The application drives the whole+lifecycle through outbound calls only; no inbound endpoint or webhook is involved.++## Before you begin++- A Databricks workspace with the sandbox feature enabled, and `databricks-sdk >= 0.153.0`.+- Python 3.11+ (the script declares its dependencies inline for `uv`).+- Two OpenAI keys, from the same organization, project, and user or service-account:+ - `OPENAI_API_KEY` - the application key that creates sessions (kept outside the sandbox).+ - `OPENAI_EXECUTOR_API_KEY` - a dedicated environment key created on the OpenAI+ Agents tab (`platform.openai.com/agents` -> Environments -> Keys), with every+ other permission set to None. It enters the sandbox as `CODEX_API_KEY`. A general+ API key does not work for the executor: it is rejected with `403 missing required+ scope api.agents.environments.connect`. See+ [executor authentication](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication).+- If your OpenAI organization enforces an IP allowlist, the sandbox's egress IP must+ be added to the allowlist; Managed Agents then rejects traffic from unregistered+ IPs. See [Databricks Outbound IPs](https://docs.databricks.com/aws/en/resources/ip-domain-region#outbound-ips)+ for the list of Databricks IPs that need to be allowlisted.++Note: the Agents API does not yet support Zero Data Retention (ZDR), including with+self-hosted sandboxes. Factor this into customer use cases.++## Configure access++The example uses a Databricks SDK config profile for the workspace and reads the+OpenAI keys from the environment:++```bash+export DATABRICKS_CONFIG_PROFILE=my-workspace # For additional Databricks authentication modes, see https://docs.databricks.com/aws/en/dev-tools/auth/+export OPENAI_API_KEY=sk-... # application key+export OPENAI_EXECUTOR_API_KEY=sk-... # agent environment key+```++## Run++From the Cookbook repository root, run with [uv](https://docs.astral.sh/uv/):++```bash+uv run examples/agents_api/sandboxes/databricks/application_managed/main.py+```++The script:++1. Creates a `self_hosted` OpenAI session with `workspace_directory` set to a path in the sandbox.+2. Provisions the sandbox (`create_sandbox`, or reuse and `start_sandbox`) and waits for it to reach `RUNNING`.+3. Creates the agent's workspace directory in the sandbox.+4. Runs `codex exec-server` in the sandbox.+5. Runs one turn: the agent writes a greeting file; the example reads it back to verify.+6. Tears down: stops the executor, deletes the session, and deletes the sandbox.++Keep the session and sandbox alive for follow-up turns. Do not attach a+provisioning webhook handler to sessions this application manages.++## References++- [Databricks Sandbox product docs](https://docs.databricks.com/aws/en/compute/serverless/sandbox)+- [Databricks SDK sandbox API](https://databricks-sdk-py.readthedocs.io/en/latest/workspace/sandbox/sandbox.html)+- [Databricks SDK sandbox command execution](https://databricks-sdk-py.readthedocs.io/en/latest/sandbox-command-execution.html)+- [Self-hosted sandboxes](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted)diff --git a/examples/agents_api/sandboxes/databricks/application_managed/__init__.py b/examples/agents_api/sandboxes/databricks/application_managed/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/examples/agents_api/sandboxes/databricks/application_managed/main.py b/examples/agents_api/sandboxes/databricks/application_managed/main.pynew file mode 100644index 00000000..979c4f9c--- /dev/null+++ b/examples/agents_api/sandboxes/databricks/application_managed/main.py@@ -0,0 +1,108 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["openai>=3.19.0", "databricks-sdk>=0.153.0"]+# ///+"""Run an OpenAI Agents API task in a Databricks sandbox (application-managed).++The application owns the whole lifecycle: it creates a self-hosted session, provisions+the sandbox and launches codex exec-server itself (all outbound calls), runs one turn,+verifies the agent's file write, then tears everything down. No inbound endpoint or+webhook is involved.+"""++from __future__ import annotations++import argparse+import asyncio+import os+import sys+from pathlib import Path++from databricks.sdk import WorkspaceClient+from openai import AsyncOpenAI++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT.parent))+from common import ( # noqa: E402 (local import after sys.path setup)+ GREETING,+ PROMPT,+ WORK_DIR,+ confirm_executor,+ delete_sandbox,+ delete_session,+ prepare_workspace,+ provision_sandbox,+ run_turn,+ start_executor,+ stop_executor,+ verify_output,+)+++async def main(args):+ executor_key = args.executor_api_key+ if not executor_key:+ raise SystemExit(+ "set OPENAI_EXECUTOR_API_KEY to an environment key created on the OpenAI "+ "Agents tab (every other permission None); a general API key is rejected with "+ "'missing required scope api.agents.environments.connect'"+ )++ workspace_client = WorkspaceClient(profile=args.profile)+ name = None+ pid = None+ session = None+ async with AsyncOpenAI(timeout=60) as client:+ try:+ session = await client.beta.agents.sessions.create(+ agent={"model": args.model},+ environment={"type": "self_hosted", "workspace_directory": WORK_DIR},+ )+ print(f"Session: {session.id}", flush=True)++ name = provision_sandbox(+ workspace_client, args.sandbox_id, inactivity_timeout_s=args.inactivity_timeout+ )+ print(f"Sandbox: {name}", flush=True)+ prepare_workspace(workspace_client, name)++ pid = start_executor(+ workspace_client,+ name,+ environment_id=session.environment.id,+ remote_url=session.environment.remote_url,+ executor_api_key=executor_key,+ )+ confirm_executor(workspace_client, name, pid)++ await run_turn(client, session.id, PROMPT)+ verify_output(workspace_client, name, GREETING)+ print("\nVerified the agent's file write.", flush=True)+ finally:+ # Nested finally so a failure in one teardown step still attempts the rest.+ try:+ if pid is not None:+ stop_executor(workspace_client, name, pid)+ finally:+ try:+ if session is not None:+ await delete_session(client, session.id)+ finally:+ if name is not None and not args.keep_sandbox:+ delete_sandbox(workspace_client, name)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--profile", default=os.environ.get("DATABRICKS_CONFIG_PROFILE"))+ parser.add_argument("--sandbox-id", default="openai-agent-sandbox")+ parser.add_argument("--model", default="gpt-5.6-sol")+ parser.add_argument("--inactivity-timeout", type=int, default=900)+ parser.add_argument(+ "--executor-api-key",+ default=os.environ.get("OPENAI_EXECUTOR_API_KEY"),+ help="OpenAI environment key passed to codex as CODEX_API_KEY. Required. "+ "Defaults to the OPENAI_EXECUTOR_API_KEY env var.",+ )+ parser.add_argument("--keep-sandbox", action="store_true", help="Do not delete the sandbox on exit")+ asyncio.run(main(parser.parse_args()))diff --git a/examples/agents_api/sandboxes/databricks/common.py b/examples/agents_api/sandboxes/databricks/common.pynew file mode 100644index 00000000..3b6d077b--- /dev/null+++ b/examples/agents_api/sandboxes/databricks/common.py@@ -0,0 +1,227 @@+"""Shared helpers for the OpenAI Agents API + Databricks sandbox examples.++Two halves:++- Databricks side: provision a sandbox and run commands in it, using only the+ released ``databricks-sdk`` unary APIs (sandbox CRUD plus+ ``execute_command_sync``). No streaming APIs are required.+- OpenAI side: drive an Agents API self-hosted session with the ``openai`` client.++The application-managed example builds on these helpers.+"""++from __future__ import annotations++import asyncio+import shlex+import time++from databricks.sdk import WorkspaceClient+from databricks.sdk.errors import NotFound+from databricks.sdk.service.sandbox import (+ ComputeSpec,+ ExecuteCommandStatus,+ Sandbox,+ SandboxSpec,+ SandboxState,+)+from google.protobuf.duration_pb2 import Duration+from openai import APIStatusError, NotFoundError++# The agent writes this greeting to a file in its workspace; we read it back to verify.+GREETING = "Hello from a Databricks sandbox!\n"+OUTPUT_PATH = "hello.txt"++# /home/sandbox-agent is a dedicated, writable volume owned by the sandbox user that+# survives stop/restart. "/" and "/tmp" are an ephemeral overlay wiped on restart, and+# $HOME defaults to a root-owned, non-writable path, so put the workspace here.+HOME_DIR = "/home/sandbox-agent"+WORK_DIR = f"{HOME_DIR}/agent-workspace"++PROMPT = f"Write {GREETING!r} to {WORK_DIR}/{OUTPUT_PATH}, then confirm you wrote it."++# codex ships in the sandbox image and is on the login-shell PATH, so launch it by+# name - no runtime install needed.+CODEX_BIN = "codex"+EXECUTOR_LOG = f"{HOME_DIR}/codex-exec-server.log"+++class SandboxCommandError(RuntimeError):+ """A command run in the sandbox did not complete successfully."""+++def run_command(workspace_client, name, script, *, envs=None, timeout_s=120, check=True):+ """Run a bash script in the sandbox via the unary ``execute_command_sync`` API.++ ``execute_command_sync`` is direct-exec (no shell, no login profile), so every+ command goes through ``/bin/bash -lc`` to get a login shell and a PATH.+ """+ response = workspace_client.sandbox.execute_command_sync(+ name,+ "/bin/bash",+ args=["-lc", script],+ envs=envs,+ execution_timeout=Duration(seconds=timeout_s),+ )+ completed = response.status == ExecuteCommandStatus.EXECUTE_COMMAND_STATUS_COMPLETED+ if check and (not completed or response.exit_code != 0):+ raise SandboxCommandError(+ f"command failed (status={response.status}, exit_code={response.exit_code}): "+ f"{response.stderr or response.stdout}"+ )+ return response+++def _wait_for_state(workspace_client, name, target, *, timeout_s=180, poll_s=3):+ deadline = time.monotonic() + timeout_s+ while time.monotonic() < deadline:+ if workspace_client.sandbox.get_sandbox(name).status.state == target:+ return+ time.sleep(poll_s)+ raise TimeoutError(f"sandbox {name} did not reach {target} within {timeout_s}s")+++def provision_sandbox(workspace_client, sandbox_id, *, inactivity_timeout_s=900):+ """Create the sandbox (or reuse and start an existing one) and wait until RUNNING."""+ name = f"sandboxes/{sandbox_id}"+ try:+ sandbox = workspace_client.sandbox.get_sandbox(name)+ except NotFound:+ sandbox = workspace_client.sandbox.create_sandbox(+ Sandbox(+ spec=SandboxSpec(+ compute=ComputeSpec(+ inactivity_timeout=Duration(seconds=inactivity_timeout_s)+ )+ )+ ),+ sandbox_id=sandbox_id,+ )+ if sandbox.status.state in (+ SandboxState.SANDBOX_STATE_STOPPED,+ SandboxState.SANDBOX_STATE_STOPPING,+ ):+ workspace_client.sandbox.start_sandbox(name)+ _wait_for_state(workspace_client, name, SandboxState.SANDBOX_STATE_RUNNING)+ return name+++def prepare_workspace(workspace_client, name, *, work_dir=WORK_DIR):+ """Create the agent's workspace directory and clear output from a prior run.++ The executor changes directory to this path for each tool call. Removing a stale+ output file first keeps verification from passing on a previous run's greeting when+ the sandbox is reused (for example with --keep-sandbox).+ """+ output = f"{work_dir}/{OUTPUT_PATH}"+ run_command(+ workspace_client, name, f"mkdir -p {shlex.quote(work_dir)}; rm -f {shlex.quote(output)}"+ )+++def _parse_pid(stdout):+ for token in stdout.split():+ if token.startswith("pid="):+ return int(token.split("=", 1)[1])+ raise SandboxCommandError(f"could not read exec-server pid from: {stdout!r}")+++def start_executor(workspace_client, name, *, environment_id, remote_url, executor_api_key):+ """Start codex exec-server detached so the sync RPC returns while it stays connected.++ exec-server holds a long-lived outbound connection to OpenAI for the whole session,+ but ``execute_command_sync`` blocks until the command exits. ``setsid nohup ... &``+ daemonizes it (new session, detached from the RPC's shell) so the call returns+ immediately. The executor key is passed via env, never written to disk.+ """+ # CODEX_HOME under the persistent home, not /tmp: codex refuses to create its+ # PATH-alias helper binaries under a temp dir.+ script = (+ f"cx=$(mktemp -d -p {HOME_DIR}); rm -f {EXECUTOR_LOG}; "+ f"CODEX_HOME=$cx setsid nohup {CODEX_BIN} exec-server "+ f"--remote {shlex.quote(remote_url)} --environment-id {shlex.quote(environment_id)} "+ f"</dev/null >{EXECUTOR_LOG} 2>&1 & echo pid=$!"+ )+ response = run_command(+ workspace_client, name, script, envs={"CODEX_API_KEY": executor_api_key, "RUST_LOG": "info"}+ )+ return _parse_pid(response.stdout)+++def confirm_executor(workspace_client, name, pid, *, settle_s=8):+ """Give the executor a moment to register, then confirm it is still running."""+ time.sleep(settle_s)+ out = run_command(+ workspace_client,+ name,+ f"if ps -p {pid} >/dev/null; then echo ALIVE; else echo DEAD; fi; "+ f"tail -n 20 {EXECUTOR_LOG}",+ ).stdout+ if "ALIVE" not in out:+ raise SandboxCommandError(f"codex exec-server exited early:\n{out}")+ return out+++def stop_executor(workspace_client, name, pid):+ run_command(+ workspace_client,+ name,+ f"kill -TERM -{pid} 2>/dev/null; kill -TERM {pid} 2>/dev/null; true",+ check=False,+ )+++def verify_output(workspace_client, name, expected=GREETING, *, work_dir=WORK_DIR):+ content = run_command(workspace_client, name, f"cat {shlex.quote(work_dir)}/{OUTPUT_PATH}").stdout+ if expected.strip() not in content:+ raise RuntimeError(f"sandbox output did not contain expected text: {content!r}")+ return content+++def delete_sandbox(workspace_client, name):+ workspace_client.sandbox.delete_sandbox(name)+++async def run_turn(client, session_id, prompt=PROMPT):+ """Submit input and stream the turn to completion, printing output text as it arrives."""+ async with asyncio.timeout(420):+ async with client.beta.agents.sessions.stream(session_id, input=prompt) as events:+ async for event in events:+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ elif event.type in {+ "agent.session.turn.completed",+ "agent.session.turn.failed",+ "agent.session.turn.cancelled",+ }:+ if event.turn.subagent_id is not None:+ continue+ if event.type != "agent.session.turn.completed":+ raise RuntimeError(f"Turn failed: {event.type}")+ print(f"\nCompleted turn: {event.turn.id}", flush=True)+ return+ elif event.type in {+ "error",+ "agent.session.failed",+ "agent.session.environment.failed",+ }:+ raise RuntimeError(f"Session failed: {event.type}")+ raise RuntimeError("Stream ended without a completed turn")+++async def delete_session(client, session_id):+ for attempt in range(10):+ try:+ await client.beta.agents.sessions.delete(session_id)+ break+ except APIStatusError as error:+ # 409 means a turn is still in progress; cancel it, let it settle, and retry.+ if error.status_code != 409 or attempt == 9:+ raise+ await client.beta.agents.sessions.cancel(session_id)+ await asyncio.sleep(2)+ try:+ await client.beta.agents.sessions.retrieve(session_id)+ except NotFoundError:+ return+ raise RuntimeError(f"Session deletion not confirmed: {session_id}")diff --git a/examples/agents_api/sandboxes/databricks/images/databricks-sandbox.png b/examples/agents_api/sandboxes/databricks/images/databricks-sandbox.pngnew file mode 100644index 00000000..6a4c2f9cBinary files /dev/null and b/examples/agents_api/sandboxes/databricks/images/databricks-sandbox.png differdiff --git a/registry.yaml b/registry.yamlindex d4dbedb7..0c38b2ee 100644--- a/registry.yaml+++ b/registry.yaml@@ -63,6 +63,18 @@- agents- sandbox+- title: Run OpenAI agents on a Databricks Sandbox+ path: examples/agents_api/sandboxes/databricks/README.md+ slug: agents-api-databricks-sandbox+ description: Run agent tools in a Databricks serverless sandbox with application-managed provisioning.+ date: 2026-10-23+ authors:+ - HsingTang+ tags:+ - agents-api+ - agents+ - sandbox+- title: Build an SRE agent for incident responsepath: examples/agents_api/apps/sev_bot/README.mdslug: agents-api-sev-bot