Examples and guides for using the OpenAI API
Add Runloop webhook-managed sandbox example (#3127)
Abdulrahman Alfozan5986832a5541
diff --git a/examples/agents_api/sandboxes/README.md b/examples/agents_api/sandboxes/README.mdindex 0c6afda9..09c55bfd 100644--- a/examples/agents_api/sandboxes/README.md+++ b/examples/agents_api/sandboxes/README.md@@ -32,7 +32,8 @@ sandboxes/├── blaxel/ # Deployable provider handler├── daytona/ # Deployable provider handler├── digitalocean/ # Deployable provider handler- └── e2b/ # Deployable provider handler+ ├── e2b/ # Deployable provider handler+ └── runloop/ # Deployable provider handler```Start with the README for your chosen mode, then the provider README. Run commandsdiff --git a/examples/agents_api/sandboxes/webhook_managed/README.md b/examples/agents_api/sandboxes/webhook_managed/README.mdindex 2093a125..13a6c52d 100644--- a/examples/agents_api/sandboxes/webhook_managed/README.md+++ b/examples/agents_api/sandboxes/webhook_managed/README.md@@ -20,6 +20,7 @@ provider account start and reconnect its sandbox.| Blaxel | [handler.py](blaxel/handler.py) | [Deploy](blaxel/README.md) || Daytona | [handler.py](daytona/handler.py) | [Deploy](daytona/README.md) || E2B | [handler.py](e2b/handler.py) | [Deploy](e2b/README.md) |+| Runloop | [handler.py](runloop/handler.py) | [Deploy](runloop/README.md) || DigitalOcean | [handler.py](digitalocean/handler.py) | [Deploy](digitalocean/README.md) |Complete the setup below, deploy one provider's handler, then run the shared@@ -63,7 +64,7 @@ client. For direct provisioning from your application, use| Variable | Where it is used || --- | --- || `OPENAI_API_KEY` | Application and controller. The application creates sessions; the controller reads their current state. |-| `OPENAI_EXECUTOR_API_KEY` | Passed to each worker as `CODEX_API_KEY`. Grant **List models → Read** and set other permissions to **None**. |+| `OPENAI_EXECUTOR_API_KEY` | An [environment key](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication), passed to each worker as `CODEX_API_KEY`. || `OPENAI_WEBHOOK_SECRET` | Controller only. Verifies deliveries from your OpenAI project. |The two API keys must have the same organization, project, and user or service-accountdiff --git a/examples/agents_api/sandboxes/webhook_managed/runloop/README.md b/examples/agents_api/sandboxes/webhook_managed/runloop/README.mdnew file mode 100644index 00000000..647911f8--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/runloop/README.md@@ -0,0 +1,67 @@+# Runloop webhook-managed sandbox++A controller in a dedicated Runloop devbox receives signed OpenAI webhooks and+queues work in SQLite. It starts or resumes a separate worker devbox for each+API session. Agent commands run only in the worker.++## Deploy++Create an agent using the [shared setup](../README.md#set-up-once). Set+`OPENAI_AGENT_ID`, `OPENAI_API_KEY`, `OPENAI_EXECUTOR_API_KEY`, and `RUNLOOP_API_KEY`+locally. Use an+[environment key](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication)+for `OPENAI_EXECUTOR_API_KEY`.++Run from the Cookbook repository root:++```bash+uv run examples/agents_api/sandboxes/webhook_managed/runloop/deploy.py+```++Register the printed URL in **OpenAI project settings → Webhooks**, subscribing to+`agent.session.action_required` and `agent.session.failed`. Set the generated+`OPENAI_WEBHOOK_SECRET` locally and deploy again. **Update the webhook URL to the+newly printed address**, keeping its signing secret. Then use the+[shared client](../README.md#run-and-reconnect).++Deployment stores credentials in Runloop secrets with the `agents_api_webhook_`+prefix. The controller accesses OpenAI through a Runloop gateway; workers receive+only the environment key as `CODEX_API_KEY` and connect directly to OpenAI.+The endpoint rejects deliveries until configured and verifies every signature.++The controller ID is saved in `.controller.json`. Changing the handler, agent ID,+Runloop key, or signing secret replaces the controller and changes its URL.+Otherwise deployment reuses it.++## Lifecycle++| Current state | Handler action |+| --- | --- |+| Connection required, no worker | Create a worker and launch the executor. |+| Connection required, suspended worker | Resume it and relaunch the executor. |+| Session failed | Shut down its worker. |+| Other agent, resolved action, or idle event | Do not provision or stop compute. |++The handler waits up to 60 seconds for connection before completing a queued job.+Failed startup gets up to five attempts. Run one controller process; its queue+survives process restarts and suspend/resume, but not controller replacement.++## Stop or clean up++Suspend a worker between turns to retain its files. The next input wakes it+through a webhook. Workers shut down after 30 minutes. The controller suspends+after ten idle minutes; HTTP requests wake it, with the first request returning+`503` for OpenAI to retry.++For final cleanup, delete the API session and shut down its worker separately.+Remove the OpenAI webhook before shutting down the controller. Delete the+`agents-api-webhook-openai-controller` gateway and the example's Runloop secrets+when no longer used.++Find controller logs in the Runloop devbox logs and executor logs in+`/tmp/codex-executor.log` inside each worker.++## References++- [Runloop documentation](https://docs.runloop.ai/)+- [Runloop Python SDK](https://runloopai.github.io/api-client-python/)diff --git a/examples/agents_api/sandboxes/webhook_managed/runloop/deploy.py b/examples/agents_api/sandboxes/webhook_managed/runloop/deploy.pynew file mode 100644index 00000000..190eda63--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/runloop/deploy.py@@ -0,0 +1,168 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "runloop-api-client>=1.31.0",+# ]+# ///++"""Deploy a signature-protected controller in a dedicated Runloop devbox."""++from __future__ import annotations++import asyncio+import hashlib+import json+import os+from pathlib import Path++from runloop_api_client import AsyncRunloopSDK, NotFoundError+from runloop_api_client.sdk.async_devbox import AsyncDevbox++ROOT = Path(__file__).parent+STATE = ROOT / ".controller.json"+CONTROLLER_NAME = "agents-api-webhook-runloop"+OPENAI_GATEWAY_NAME = "agents-api-webhook-openai-controller"+OPENAI_SECRET_NAME = "agents_api_webhook_openai_api_key"+OPENAI_EXECUTOR_SECRET_NAME = "agents_api_webhook_openai_executor_api_key"+RUNLOOP_SECRET_NAME = "agents_api_webhook_runloop_api_key"+WEBHOOK_SECRET_NAME = "agents_api_webhook_openai_webhook_secret"+++async def ensure_gateway(runloop: AsyncRunloopSDK) -> str:+ async for info in await runloop.api.gateway_configs.list(+ name=OPENAI_GATEWAY_NAME,+ include_total_count=False,+ ):+ if info.name == OPENAI_GATEWAY_NAME:+ return info.id+ return (+ await runloop.gateway_config.create(+ name=OPENAI_GATEWAY_NAME,+ endpoint="https://api.openai.com",+ auth_mechanism={"type": "bearer"},+ )+ ).id+++async def wait_for_controller(controller: AsyncDevbox) -> None:+ for _ in range(30):+ info = await controller.get_info()+ if info.status == "failure":+ raise RuntimeError("Controller entrypoint failed; inspect the devbox logs")+ try:+ health = await controller.cmd.exec("curl -fsS http://127.0.0.1:8000/health")+ except Exception: # noqa: BLE001 - Retry while the devbox is starting.+ health = None+ if health is not None and health.exit_code == 0:+ return+ await asyncio.sleep(2)+ raise TimeoutError("Controller did not become healthy before the retry limit")+++async def reuse_saved_controller(+ runloop: AsyncRunloopSDK,+ state: dict[str, str] | None,+ fingerprint: str,+) -> AsyncDevbox | None:+ if state is None:+ return None+ controller = runloop.devbox.from_id(state["devbox_id"])+ try:+ info = await controller.get_info()+ except NotFoundError:+ return None+ if info.status in {"failure", "shutdown"}:+ return None+ if state.get("fingerprint") != fingerprint:+ await controller.shutdown()+ return None+ if info.status == "suspended":+ await controller.resume()+ elif info.status == "suspending":+ await controller.await_suspended()+ await controller.resume()+ elif info.status != "running":+ await controller.await_running()+ return controller+++async def main() -> None:+ handler = ROOT.joinpath("handler.py").read_text()+ agent_id = os.environ["OPENAI_AGENT_ID"]+ values = {+ OPENAI_SECRET_NAME: os.environ["OPENAI_API_KEY"],+ OPENAI_EXECUTOR_SECRET_NAME: os.environ["OPENAI_EXECUTOR_API_KEY"],+ RUNLOOP_SECRET_NAME: os.environ["RUNLOOP_API_KEY"],+ WEBHOOK_SECRET_NAME: os.environ.get(+ "OPENAI_WEBHOOK_SECRET", "pending-webhook-registration"+ ),+ }+ async with AsyncRunloopSDK() as runloop:+ for name, value in values.items():+ try:+ await runloop.secret.update(name, value)+ except NotFoundError:+ await runloop.secret.create(name, value)+ gateway_id = await ensure_gateway(runloop)+ # These values are fixed at creation; replace the controller when they change.+ fingerprint = hashlib.sha256(+ "\0".join(+ [+ values[RUNLOOP_SECRET_NAME],+ values[WEBHOOK_SECRET_NAME],+ agent_id,+ handler,+ gateway_id,+ ]+ ).encode()+ ).hexdigest()+ state = json.loads(STATE.read_text()) if STATE.exists() else None+ controller = await reuse_saved_controller(runloop, state, fingerprint)+ if controller is None:+ controller = await runloop.devbox.create(+ name=CONTROLLER_NAME,+ environment_variables={"OPENAI_AGENT_ID": agent_id},+ secrets={+ "RUNLOOP_API_KEY": RUNLOOP_SECRET_NAME,+ "OPENAI_WEBHOOK_SECRET": WEBHOOK_SECRET_NAME,+ },+ gateways={+ "OPENAI_GATEWAY": {+ "gateway": gateway_id,+ "secret": OPENAI_SECRET_NAME,+ }+ },+ file_mounts={"/home/user/controller/handler.py": handler},+ entrypoint="cd /home/user/controller && exec uv run handler.py",+ tunnel={"auth_mode": "open"},+ launch_parameters={+ "launch_commands": [+ (+ "dpkg -s libsqlite3-0 >/dev/null 2>&1 || "+ "(sudo apt-get update && sudo apt-get install -y libsqlite3-0)"+ ),+ "command -v uv || python -m pip install uv",+ ],+ "lifecycle": {+ "after_idle": {+ "idle_time_seconds": 600,+ "on_idle": "suspend",+ },+ "resume_triggers": {"http": True},+ },+ },+ )+ STATE.write_text(+ json.dumps({"devbox_id": controller.id, "fingerprint": fingerprint})+ + "\n"+ )+ await wait_for_controller(controller)+ webhook_url = await controller.get_tunnel_url(8000)+ if webhook_url is None:+ raise RuntimeError("Controller tunnel was not provisioned")+ print(f"Webhook: {webhook_url}/webhook")+ print(f"Controller: {controller.id} (suspends after ten idle minutes)")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/webhook_managed/runloop/handler.py b/examples/agents_api/sandboxes/webhook_managed/runloop/handler.pynew file mode 100644index 00000000..9fcd9306--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/runloop/handler.py@@ -0,0 +1,252 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "fastapi>=0.115,<1",+# "openai>=3.13.0",+# "runloop-api-client>=1.31.0",+# "uvicorn>=0.30,<1",+# ]+# ///++"""A single-process OpenAI webhook controller hosted in a Runloop devbox."""++from __future__ import annotations++import asyncio+import json+import os+import shlex+import sqlite3+import time+import traceback+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager++from fastapi import FastAPI, Request+from fastapi.responses import JSONResponse+from openai import AsyncOpenAI, InvalidWebhookSignatureError, NotFoundError, OpenAI+from runloop_api_client import AsyncRunloopSDK+from runloop_api_client.lib.polling import PollingConfig+from runloop_api_client.sdk.async_devbox import AsyncDevbox+from runloop_api_client.sdk.async_execution import AsyncExecution++DB_PATH = os.environ.get("QUEUE_PATH", "/home/user/pending.sqlite3")+OPENAI_EXECUTOR_SECRET_NAME = "agents_api_webhook_openai_executor_api_key"+CODEX = "/home/user/.codex-runtime/node_modules/.bin/codex"+EXECUTOR_CONNECT_TIMEOUT = 60+LOCK_BUSY_EXIT_CODE = 75+++def log(**fields: object) -> None:+ print(json.dumps(fields), flush=True)+++async def find_devbox(+ runloop: AsyncRunloopSDK, session_id: str+) -> tuple[AsyncDevbox | None, str | None]:+ async for info in await runloop.api.devboxes.list(include_total_count=False):+ if info.status not in {"failure", "shutdown"} and (+ (info.metadata or {}).get("agents-session-id") == session_id+ ):+ return runloop.devbox.from_id(info.id), info.status+ return None, None+++async def wait_for_executor(+ client: AsyncOpenAI, session_id: str, execution: AsyncExecution+) -> None:+ async with asyncio.timeout(EXECUTOR_CONNECT_TIMEOUT):+ while True:+ session = await client.beta.agents.sessions.retrieve(session_id)+ if session.status == "failed":+ raise RuntimeError("Session failed before the executor connected")+ if not any(+ action.type == "environment_connection"+ for action in session.required_actions+ ):+ return+ state = await execution.get_state()+ # A duplicate launch loses the lock; wait for the existing executor.+ if state.status == "completed" and state.exit_status != LOCK_BUSY_EXIT_CODE:+ raise RuntimeError("Executor exited; inspect /tmp/codex-executor.log")+ await asyncio.sleep(2)+++async def reconcile(session_id: str) -> None:+ async with (+ AsyncOpenAI(+ api_key=os.environ["OPENAI_GATEWAY"],+ base_url=f"{os.environ['OPENAI_GATEWAY_URL'].rstrip('/')}/v1",+ timeout=30,+ ) as client,+ AsyncRunloopSDK() as runloop,+ ):+ try:+ session = await client.beta.agents.sessions.retrieve(session_id)+ except NotFoundError:+ return+ if (+ session.environment.type != "self_hosted"+ or session.agent.id != os.environ["OPENAI_AGENT_ID"]+ ):+ return+ if session.status != "failed" and not any(+ action.type == "environment_connection"+ for action in session.required_actions+ ):+ return+ devbox, status = await find_devbox(runloop, session_id)+ if session.status == "failed":+ if devbox is not None:+ await devbox.shutdown()+ return+ if devbox is None:+ devbox = await runloop.devbox.create(+ name=f"agents-webhook-{session_id[-24:]}",+ metadata={"agents-session-id": session_id},+ secrets={"CODEX_API_KEY": OPENAI_EXECUTOR_SECRET_NAME},+ launch_parameters={"keep_alive_time_seconds": 1800},+ )+ elif status == "suspended":+ await devbox.resume()+ elif status == "suspending":+ await devbox.await_suspended()+ await devbox.resume()+ elif status != "running":+ await devbox.await_running()+ setup = await devbox.cmd.exec(+ "sudo install -d -o user -g user /workspace && "+ "mkdir -p /home/user/.codex-runtime && "+ f"(test -x {CODEX} || "+ "npm install --prefix /home/user/.codex-runtime @openai/codex@alpha) && "+ "command -v flock",+ polling_config=PollingConfig(timeout_seconds=180),+ )+ if setup.exit_code != 0:+ raise RuntimeError("Executor installation failed")+ environment_id = shlex.quote(session.environment.id)+ remote_url = shlex.quote(session.environment.remote_url)+ execution = await devbox.cmd.exec_async(+ f"cd /workspace && flock -n -E {LOCK_BUSY_EXIT_CODE} /tmp/codex-executor.lock "+ f"{CODEX} exec-server "+ f"--remote {remote_url} "+ f"--environment-id {environment_id} "+ ">> /tmp/codex-executor.log 2>&1"+ )+ await wait_for_executor(client, session_id, execution)+ log(session_id=session_id, devbox_id=devbox.id, action="connected")+++def initialize_queue(db: sqlite3.Connection) -> None:+ db.execute(+ "CREATE TABLE IF NOT EXISTS jobs ("+ "session_id TEXT PRIMARY KEY, "+ "attempts INTEGER DEFAULT 0, "+ "retry_at REAL DEFAULT 0, "+ "generation INTEGER DEFAULT 0)"+ )+ db.commit()+++def enqueue(db: sqlite3.Connection, session_id: str) -> None:+ db.execute(+ "INSERT INTO jobs(session_id) VALUES (?) "+ "ON CONFLICT(session_id) DO UPDATE SET "+ "attempts = 0, retry_at = 0, generation = jobs.generation + 1",+ (session_id,),+ )+ db.commit()+++async def process_next_job(db: sqlite3.Connection) -> bool:+ row = db.execute(+ "SELECT session_id, attempts, generation FROM jobs WHERE retry_at <= ? LIMIT 1",+ (time.time(),),+ ).fetchone()+ if row is None:+ return False+ session_id, attempts, generation = row+ try:+ await reconcile(session_id)+ except Exception as error: # noqa: BLE001 - Keep failed jobs in the retry queue.+ if attempts >= 4:+ db.execute(+ "DELETE FROM jobs WHERE session_id = ? AND generation = ?",+ (session_id, generation),+ )+ else:+ db.execute(+ "UPDATE jobs SET attempts = ?, retry_at = ? "+ "WHERE session_id = ? AND generation = ?",+ (attempts + 1, time.time() + 10, session_id, generation),+ )+ log(+ session_id=session_id,+ error_type=type(error).__name__,+ error_at=[+ f"{frame.name}:{frame.lineno}"+ for frame in traceback.extract_tb(error.__traceback__)+ ],+ )+ else:+ db.execute(+ "DELETE FROM jobs WHERE session_id = ? AND generation = ?",+ (session_id, generation),+ )+ db.commit()+ return True+++async def drain_queue(db: sqlite3.Connection) -> None:+ while True:+ if not await process_next_job(db):+ await asyncio.sleep(1)+++@asynccontextmanager+async def lifespan(app: FastAPI) -> AsyncIterator[None]:+ db = sqlite3.connect(DB_PATH)+ initialize_queue(db)+ app.state.db = db+ task = asyncio.create_task(drain_queue(db))+ try:+ yield+ finally:+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ db.close()+++app = FastAPI(lifespan=lifespan)++[email protected]("/health")+async def health() -> dict[str, bool]:+ return {"ok": True}++[email protected]("/webhook")+async def webhook(request: Request) -> JSONResponse:+ secret = os.environ.get("OPENAI_WEBHOOK_SECRET")+ if not secret or secret == "pending-webhook-registration":+ return JSONResponse({"error": "Webhook not configured"}, status_code=503)+ payload = (await request.body()).decode()+ with OpenAI(api_key="unused", webhook_secret=secret) as verifier:+ try:+ verifier.webhooks.verify_signature(payload=payload, headers=request.headers)+ except (InvalidWebhookSignatureError, ValueError):+ return JSONResponse({"error": "Invalid signature"}, status_code=400)+ event = json.loads(payload)+ if event["type"] == "agent.session.failed" or (+ event["type"] == "agent.session.action_required"+ and event["data"]["required_action"]["type"] == "environment_connection"+ ):+ enqueue(request.app.state.db, event["data"]["id"])+ log(event_id=event["id"], session_id=event["data"]["id"], action="enqueued")+ return JSONResponse({"ok": True})+++if __name__ == "__main__":+ import uvicorn++ uvicorn.run(app, host="0.0.0.0", port=8000)