Skip to content

Examples and guides for using the OpenAI API

chore(agents-api): remove Runloop sandbox examples (#3191)

td293fc83ebf64
diff --git a/examples/agents_api/sandboxes/README.md b/examples/agents_api/sandboxes/README.md
index 8f2349d6..ed93e9c2 100644
--- a/examples/agents_api/sandboxes/README.md
+++ b/examples/agents_api/sandboxes/README.md
@@ -24,7 +24,6 @@ provider compute; each example documents cleanup of both.
| [Modal](modal/README.md) | [Run](modal/application_managed/README.md) | [Deploy](modal/webhook_managed/README.md) |
| [AWS Lambda MicroVMs](aws/README.md) | [Run](aws/application_managed/README.md) | [Deploy](aws/webhook_managed/README.md) |
| [OCI](oci/README.md) | [Run](oci/application_managed/README.md) | Not included |
-| [Runloop](runloop/README.md) | [Run](runloop/application_managed/README.md) | [Deploy](runloop/webhook_managed/README.md) |
| [Vercel](vercel/README.md) | [Run](vercel/application_managed/README.md) | [Deploy](vercel/webhook_managed/README.md) |
Each provider folder contains its examples and shared sandbox setup. Webhook
diff --git a/examples/agents_api/sandboxes/runloop/README.md b/examples/agents_api/sandboxes/runloop/README.md
deleted file mode 100644
index 29325eb0..00000000
--- a/examples/agents_api/sandboxes/runloop/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# Runloop sandboxes
-
-Run Agents API tasks in Runloop devboxes with either provisioning model:
-
-- [Application-managed](application_managed/README.md): the application creates
- a devbox, runs a task, and cleans up the devbox and API session.
-- [Webhook-managed](webhook_managed/README.md): a signed webhook controller
- creates or resumes a worker devbox for each session.
-
-Both modes use [sandbox.py](sandbox.py) to install and launch `codex exec-server`.
-Application-managed tasks use `/home/user/workspace` and pass the restricted
-executor key as an environment variable. Webhook-managed workers use `/workspace`
-and a Runloop secret reference; the controller's main API key stays behind a
-Runloop gateway.
diff --git a/examples/agents_api/sandboxes/runloop/application_managed/README.md b/examples/agents_api/sandboxes/runloop/application_managed/README.md
deleted file mode 100644
index 338dec24..00000000
--- a/examples/agents_api/sandboxes/runloop/application_managed/README.md
+++ /dev/null
@@ -1,32 +0,0 @@
-# Application-managed Runloop sandbox
-
-The application creates an Agents API session and a Runloop devbox, starts
-`codex exec-server`, and asks the agent to turn `brief.txt` into `plan.md`.
-It prints the plan, shuts down the devbox, and deletes the session.
-
-## Run
-
-Set `RUNLOOP_API_KEY`, `OPENAI_API_KEY`, and a separate restricted
-`OPENAI_EXECUTOR_API_KEY`. The OpenAI keys must have the same owner,
-organization, and project. Only the executor key enters the devbox. See
-[executor authentication](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication).
-
-From the Cookbook repository root, run with [uv](https://docs.astral.sh/uv/):
-
-```bash
-uv run examples/agents_api/sandboxes/runloop/application_managed/main.py
-```
-
-The script declares its dependencies inline, including the Agents API SDK.
-It allows five minutes for setup and execution, then attempts cleanup of both
-resources. The devbox also has a ten-minute lifetime as a fallback if the
-application exits unexpectedly.
-
-This example uses application-managed provisioning. Do not attach a provisioning
-webhook handler to its sessions. For follow-up turns, keep the session and devbox
-alive until the application is finished.
-
-## References
-
-- [Runloop documentation](https://docs.runloop.ai/)
-- [Runloop Python SDK](https://runloopai.github.io/api-client-python/)
diff --git a/examples/agents_api/sandboxes/runloop/application_managed/main.py b/examples/agents_api/sandboxes/runloop/application_managed/main.py
deleted file mode 100644
index 11e21b66..00000000
--- a/examples/agents_api/sandboxes/runloop/application_managed/main.py
+++ /dev/null
@@ -1,89 +0,0 @@
-# /// script
-# requires-python = ">=3.11"
-# dependencies = [
-# "openai>=3.13.0",
-# "runloop-api-client>=1.31.0",
-# ]
-# ///
-
-"""Run an Agents API task in a Runloop devbox and clean up both resources."""
-
-import asyncio
-import os
-import sys
-from pathlib import Path
-
-from openai import AsyncOpenAI
-from runloop_api_client import AsyncRunloopSDK
-
-sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from sandbox import install_executor, start_executor
-
-WORKSPACE = "/home/user/workspace"
-
-
-async def main() -> None:
- executor_key = os.environ["OPENAI_EXECUTOR_API_KEY"]
- async with AsyncOpenAI(timeout=360) as client, AsyncRunloopSDK() as runloop:
- session = await client.beta.agents.sessions.create(
- agent={"model": "gpt-5.6-sol"},
- environment={"type": "self_hosted", "workspace_directory": WORKSPACE},
- )
- devbox = None
- print(f"Session: {session.id}", flush=True)
- try:
- assert session.environment.type == "self_hosted"
- async with asyncio.timeout(300):
- devbox = await runloop.devbox.create(
- name=f"agents-api-{session.id[-12:]}",
- environment_variables={"CODEX_API_KEY": executor_key},
- launch_parameters={"keep_alive_time_seconds": 600},
- )
- print(f"Devbox: {devbox.id}", flush=True)
- setup = await devbox.cmd.exec(f"mkdir -p {WORKSPACE}")
- if setup.exit_code != 0:
- raise RuntimeError("Workspace setup failed")
- await install_executor(devbox)
- await devbox.file.write(
- file_path=f"{WORKSPACE}/brief.txt",
- contents="Migrate a synchronous Python service to async without changing its API.\n",
- )
- await start_executor(
- devbox,
- workspace=WORKSPACE,
- remote_url=session.environment.remote_url,
- environment_id=session.environment.id,
- )
-
- async with client.beta.agents.sessions.stream(
- session.id,
- input="Read brief.txt and write a five-step migration plan to plan.md.",
- ) as events:
- async for event in events:
- if event.type in {
- "error",
- "agent.session.environment.failed",
- "agent.session.failed",
- "agent.session.turn.failed",
- "agent.session.turn.cancelled",
- }:
- raise RuntimeError(f"Agent failed: {event.type}")
- if event.type == "agent.session.turn.output_text.delta":
- print(event.delta, end="", flush=True)
-
- plan = await devbox.file.read(file_path=f"{WORKSPACE}/plan.md")
- if not plan.strip():
- raise RuntimeError("The agent did not write a migration plan")
- print(f"\n\nplan.md:\n{plan}")
- finally:
- try:
- if devbox is not None:
- async with asyncio.timeout(30):
- await devbox.shutdown()
- finally:
- async with asyncio.timeout(30):
- await client.beta.agents.sessions.delete(session.id)
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/examples/agents_api/sandboxes/runloop/sandbox.py b/examples/agents_api/sandboxes/runloop/sandbox.py
deleted file mode 100644
index b1a81d06..00000000
--- a/examples/agents_api/sandboxes/runloop/sandbox.py
+++ /dev/null
@@ -1,49 +0,0 @@
-"""Executor installation and launch shared by the Runloop examples."""
-
-import shlex
-
-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
-
-CODEX = "/home/user/.codex-runtime/node_modules/.bin/codex"
-LOCK_BUSY_EXIT_CODE = 75
-
-
-async def install_executor(devbox: AsyncDevbox) -> None:
- setup = await devbox.cmd.exec(
- "mkdir -p /home/user/.codex-runtime && "
- f"(test -x {CODEX} || "
- "npm install --prefix /home/user/.codex-runtime @openai/codex@alpha)",
- polling_config=PollingConfig(timeout_seconds=180),
- )
- if setup.exit_code != 0:
- raise RuntimeError("Executor installation failed")
-
-
-async def start_executor(
- devbox: AsyncDevbox,
- *,
- workspace: str,
- remote_url: str,
- environment_id: str,
- locked: bool = False,
-) -> AsyncExecution:
- command = shlex.join(
- [
- CODEX,
- "exec-server",
- "--remote",
- remote_url,
- "--environment-id",
- environment_id,
- ]
- )
- if locked:
- command = (
- f"flock -n -E {LOCK_BUSY_EXIT_CODE} /tmp/codex-executor.lock {command} "
- ">> /tmp/codex-executor.log 2>&1"
- )
- else:
- command = f"exec {command}"
- return await devbox.cmd.exec_async(f"cd {shlex.quote(workspace)} && {command}")
diff --git a/examples/agents_api/sandboxes/runloop/webhook_managed/README.md b/examples/agents_api/sandboxes/runloop/webhook_managed/README.md
deleted file mode 100644
index 318b7a46..00000000
--- a/examples/agents_api/sandboxes/runloop/webhook_managed/README.md
+++ /dev/null
@@ -1,75 +0,0 @@
-# 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](../../webhook_managed.md#set-up-once)
-and this folder's `client.py`. 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/runloop/webhook_managed/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
-[run-and-reconnect steps](../../webhook_managed.md#run-and-reconnect) with the
-provider-local client:
-
-```bash
-uv run examples/agents_api/sandboxes/runloop/webhook_managed/client.py \
- --agent-id "$OPENAI_AGENT_ID"
-```
-
-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, shared
-`sandbox.py`, agent ID, Runloop key, or signing secret replaces the controller
-and changes its URL. Otherwise deployment reuses it. The deploy script uploads
-both Python files, preserving their layout.
-
-## 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/runloop/webhook_managed/client.py b/examples/agents_api/sandboxes/runloop/webhook_managed/client.py
deleted file mode 100644
index fb62b24f..00000000
--- a/examples/agents_api/sandboxes/runloop/webhook_managed/client.py
+++ /dev/null
@@ -1,83 +0,0 @@
-# /// script
-# requires-python = ">=3.11"
-# dependencies = [
-# "openai>=3.13.0",
-# ]
-# ///
-
-"""Use Agents API without importing a sandbox provider SDK."""
-
-from __future__ import annotations
-
-import argparse
-import asyncio
-import json
-
-from openai import AsyncOpenAI
-
-
-async def main() -> None:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--create-agent", metavar="NAME")
- parser.add_argument("--agent-id")
- parser.add_argument("--session-id")
- parser.add_argument("--delete", action="store_true")
- parser.add_argument("--model", default="gpt-5.6-sol")
- parser.add_argument("--workspace", default="/workspace")
- parser.add_argument(
- "--input", default="Run a shell command to print hello from the sandbox."
- )
- args = parser.parse_args()
-
- async with AsyncOpenAI(timeout=600) as client:
- if args.create_agent:
- agent = await client.beta.agents.create(
- model=args.model, name=args.create_agent
- )
- print(json.dumps({"agent_id": agent.id}))
- return
- if args.delete:
- if not args.session_id:
- parser.error(
- "--delete requires --session-id; stop provider compute separately"
- )
- await client.beta.agents.sessions.delete(args.session_id)
- print(json.dumps({"deleted": args.session_id}))
- return
- if args.session_id:
- session = await client.beta.agents.sessions.retrieve(args.session_id)
- else:
- if not args.agent_id:
- parser.error(
- "Pass --agent-id from --create-agent, or an existing --session-id"
- )
- session = await client.beta.agents.sessions.create(
- agent_id=args.agent_id,
- environment={
- "type": "self_hosted",
- "workspace_directory": args.workspace,
- },
- )
- print(json.dumps({"session_id": session.id}), flush=True)
- completed = False
- async with client.beta.agents.sessions.stream(
- session.id, input=args.input
- ) as events:
- async for event in events:
- if event.type in {
- "agent.session.turn.failed",
- "agent.session.turn.cancelled",
- "agent.session.failed",
- }:
- raise RuntimeError(f"Agent failed: {event.type}")
- if event.type == "agent.session.turn.output_text.delta":
- print(event.delta, end="", flush=True)
- if event.type == "agent.session.turn.completed":
- completed = True
- if not completed:
- raise RuntimeError("Stream ended without a completed turn")
- print()
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/examples/agents_api/sandboxes/runloop/webhook_managed/deploy.py b/examples/agents_api/sandboxes/runloop/webhook_managed/deploy.py
deleted file mode 100644
index b0d0cbc3..00000000
--- a/examples/agents_api/sandboxes/runloop/webhook_managed/deploy.py
+++ /dev/null
@@ -1,175 +0,0 @@
-# /// 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()
- sandbox = ROOT.parent.joinpath("sandbox.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,
- sandbox,
- 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/webhook_managed/handler.py": handler,
- "/home/user/controller/sandbox.py": sandbox,
- },
- entrypoint=(
- "cd /home/user/controller/webhook_managed && 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/runloop/webhook_managed/handler.py b/examples/agents_api/sandboxes/runloop/webhook_managed/handler.py
deleted file mode 100644
index 24c66678..00000000
--- a/examples/agents_api/sandboxes/runloop/webhook_managed/handler.py
+++ /dev/null
@@ -1,247 +0,0 @@
-# /// 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 sqlite3
-import sys
-import time
-import traceback
-from collections.abc import AsyncIterator
-from contextlib import asynccontextmanager
-from pathlib import Path
-
-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.sdk.async_devbox import AsyncDevbox
-from runloop_api_client.sdk.async_execution import AsyncExecution
-
-sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from sandbox import LOCK_BUSY_EXIT_CODE, install_executor, start_executor
-
-DB_PATH = os.environ.get("QUEUE_PATH", "/home/user/pending.sqlite3")
-OPENAI_EXECUTOR_SECRET_NAME = "agents_api_webhook_openai_executor_api_key"
-EXECUTOR_CONNECT_TIMEOUT = 60
-
-
-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 && command -v flock"
- )
- if setup.exit_code != 0:
- raise RuntimeError("Workspace setup failed")
- await install_executor(devbox)
- execution = await start_executor(
- devbox,
- workspace="/workspace",
- remote_url=session.environment.remote_url,
- environment_id=session.environment.id,
- locked=True,
- )
- 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)
-
-
-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)
diff --git a/examples/agents_api/sandboxes/webhook_managed.md b/examples/agents_api/sandboxes/webhook_managed.md
index 632a2aa3..f53218d2 100644
--- a/examples/agents_api/sandboxes/webhook_managed.md
+++ b/examples/agents_api/sandboxes/webhook_managed.md
@@ -20,7 +20,6 @@ provider account start and reconnect its sandbox.
| Blaxel | [handler.py](blaxel/webhook_managed/handler.py) | [Deploy](blaxel/webhook_managed/README.md) |
| Daytona | [handler.py](daytona/webhook_managed/handler.py) | [Deploy](daytona/webhook_managed/README.md) |
| E2B | [handler.py](e2b/webhook_managed/handler.py) | [Deploy](e2b/webhook_managed/README.md) |
-| Runloop | [handler.py](runloop/webhook_managed/handler.py) | [Deploy](runloop/webhook_managed/README.md) |
| DigitalOcean | [handler.py](digitalocean/webhook_managed/handler.py) | [Deploy](digitalocean/webhook_managed/README.md) |
Complete the setup below, deploy one provider's handler, then run its