Examples and guides for using the OpenAI API
Update Agents API apps (#3082)
Abdulrahman Alfozanec3512cdd21a
diff --git a/examples/agents_api/apps/document_review/.env.example b/examples/agents_api/apps/document_review/.env.exampleindex ed6ed73b..5f5d763d 100644--- a/examples/agents_api/apps/document_review/.env.example+++ b/examples/agents_api/apps/document_review/.env.example@@ -1 +1,2 @@OPENAI_API_KEY=sk-...+OPENAI_EXECUTOR_API_KEY=sk-...diff --git a/examples/agents_api/apps/document_review/README.md b/examples/agents_api/apps/document_review/README.mdindex ec9d5753..5996e6f1 100644--- a/examples/agents_api/apps/document_review/README.md+++ b/examples/agents_api/apps/document_review/README.md@@ -24,7 +24,7 @@ sequenceDiagram- Python 3.14+ and `uv`.- A sandbox: self-hosted Docker or a [third-party provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).-- An OpenAI API key.+- An OpenAI API key and a separate restricted executor key.## 1. Set up the workspace@@ -35,7 +35,9 @@ cp examples/agents_api/apps/document_review/.env.example examples/agents_api/appdocker build -t agent-api-sandbox:latest examples/agents_api/sandboxes/application_managed/docker```-Add your OpenAI API key to `examples/agents_api/apps/document_review/.env`. The application loads this file automatically.+Set `OPENAI_API_KEY` and `OPENAI_EXECUTOR_API_KEY` in `examples/agents_api/apps/document_review/.env`. Use keys with the same owner, organization, and project. Only the executor key enters the sandbox. It needs `api.agents.environments.connect` and IP restrictions that allow the sandbox's outbound network. The application loads this file automatically.++To create an executor key with the required permission, open [Agents > Environments > Keys](https://platform.openai.com/agents?tab=environments&environment_view=keys) and select **Create**.You can replace local Docker with any compatible [sandbox provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).diff --git a/examples/agents_api/apps/document_review/agent.py b/examples/agents_api/apps/document_review/agent.pyindex d155eb61..8fc91118 100644--- a/examples/agents_api/apps/document_review/agent.py+++ b/examples/agents_api/apps/document_review/agent.py@@ -6,11 +6,13 @@ import asyncioimport jsonimport loggingimport os+import sysfrom pathlib import Pathfrom typing import Any+from docker.errors import NotFound as ContainerNotFoundfrom docker.models.containers import Container-from openai import AsyncOpenAI+from openai import AsyncOpenAI, NotFoundErrorfrom .sandbox import SKILLS_DIRECTORY, start_executor@@ -218,10 +220,30 @@ and summarize the most important findings for the human approver."output_directory": str(output_directory),}finally:+ original_error = sys.exception()+ cleanup_errors: list[Exception] = []try:if container is not None:- await asyncio.to_thread(container.stop)- logger.info("Sandbox stopped: %s", container.short_id)- finally:+ await asyncio.to_thread(container.remove, force=True)+ logger.info("Sandbox removed: %s", container.short_id)+ except ContainerNotFound:+ pass+ except Exception as error:+ cleanup_errors.append(error)+ try:await client.beta.agents.sessions.delete(session.id)logger.info("Session deleted: %s", session.id)+ except NotFoundError:+ pass+ except Exception as error:+ cleanup_errors.append(error)+ if original_error is not None:+ for error in cleanup_errors:+ original_error.add_note(+ f"Cleanup for session {session.id}: {error}"+ )+ elif cleanup_errors:+ raise ExceptionGroup(+ f"Could not clean up session {session.id} and its sandbox",+ cleanup_errors,+ )diff --git a/examples/agents_api/apps/document_review/sandbox.py b/examples/agents_api/apps/document_review/sandbox.pyindex 8be43cf1..17a762e3 100644--- a/examples/agents_api/apps/document_review/sandbox.py+++ b/examples/agents_api/apps/document_review/sandbox.py@@ -25,7 +25,7 @@ def start_executor("--environment-id",environment_id,],- environment={"CODEX_API_KEY": os.environ["OPENAI_API_KEY"]},+ environment={"CODEX_API_KEY": os.environ["OPENAI_EXECUTOR_API_KEY"]},volumes={str(input_directory.resolve()): {"bind": "/workspace/input", "mode": "ro"},str(output_directory.resolve()): {diff --git a/examples/agents_api/apps/github_issues/.env.example b/examples/agents_api/apps/github_issues/.env.exampleindex e0604530..5c2f7298 100644--- a/examples/agents_api/apps/github_issues/.env.example+++ b/examples/agents_api/apps/github_issues/.env.example@@ -1,3 +1,4 @@OPENAI_API_KEY=sk-...+OPENAI_EXECUTOR_API_KEY=sk-...GITHUB_TOKEN=github_pat_...GITHUB_WEBHOOK_SECRET=...diff --git a/examples/agents_api/apps/github_issues/README.md b/examples/agents_api/apps/github_issues/README.mdindex 92a676a2..5e3ddeed 100644--- a/examples/agents_api/apps/github_issues/README.md+++ b/examples/agents_api/apps/github_issues/README.md@@ -22,7 +22,7 @@ sequenceDiagram- Python 3.14+ and `uv`.- A sandbox: self-hosted Docker or a [third-party provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).-- An OpenAI API key.+- An OpenAI API key and a separate restricted executor key.- A GitHub token and webhook secret when you connect a real repository.## 1. Set up the investigator@@ -34,7 +34,9 @@ cp examples/agents_api/apps/github_issues/.env.example examples/agents_api/apps/docker build -t agent-api-sandbox:latest examples/agents_api/sandboxes/application_managed/docker```-Add your OpenAI API key to `examples/agents_api/apps/github_issues/.env`. You can also replace Docker with a compatible [sandbox provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).+Set `OPENAI_API_KEY` and `OPENAI_EXECUTOR_API_KEY` in `examples/agents_api/apps/github_issues/.env`. Use keys with the same owner, organization, and project. Only the executor key enters the sandbox. It needs `api.agents.environments.connect` and IP restrictions that allow the sandbox's outbound network. You can also replace Docker with a compatible [sandbox provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).++To create an executor key with the required permission, open [Agents > Environments > Keys](https://platform.openai.com/agents?tab=environments&environment_view=keys) and select **Create**.## 2. Investigate the included issuediff --git a/examples/agents_api/apps/github_issues/agent.py b/examples/agents_api/apps/github_issues/agent.pyindex cea37cca..3363f36e 100644--- a/examples/agents_api/apps/github_issues/agent.py+++ b/examples/agents_api/apps/github_issues/agent.py@@ -4,12 +4,13 @@ from __future__ import annotationsimport asyncioimport os+import sysfrom pathlib import Pathfrom typing import Anyimport dockerfrom docker.models.containers import Container-from openai import AsyncOpenAI+from openai import AsyncOpenAI, NotFoundErrorINSTRUCTIONS = """\Investigate GitHub issues by inspecting the repository and reproducing problems when practical.@@ -30,7 +31,7 @@ def start_executor(workspace: Path, environment_id: str, remote_url: str) -> Con"--environment-id",environment_id,],- environment={"CODEX_API_KEY": os.environ["OPENAI_API_KEY"]},+ environment={"CODEX_API_KEY": os.environ["OPENAI_EXECUTOR_API_KEY"]},volumes={str(workspace.resolve()): {"bind": "/workspace", "mode": "rw"}},detach=True,auto_remove=True,@@ -99,8 +100,28 @@ Inspect /workspace, run relevant tests, identify the root cause, and write"findings": report.read_text(),}finally:+ original_error = sys.exception()+ cleanup_errors: list[Exception] = []try:if container is not None:- await asyncio.to_thread(container.stop)- finally:+ await asyncio.to_thread(container.remove, force=True)+ except docker.errors.NotFound:+ pass+ except Exception as error:+ cleanup_errors.append(error)+ try:await client.beta.agents.sessions.delete(session.id)+ except NotFoundError:+ pass+ except Exception as error:+ cleanup_errors.append(error)+ if original_error is not None:+ for error in cleanup_errors:+ original_error.add_note(+ f"Cleanup for session {session.id}: {error}"+ )+ elif cleanup_errors:+ raise ExceptionGroup(+ f"Could not clean up session {session.id} and its sandbox",+ cleanup_errors,+ )diff --git a/examples/agents_api/apps/sev_bot/.env.example b/examples/agents_api/apps/sev_bot/.env.exampleindex 6f163faa..cf561923 100644--- a/examples/agents_api/apps/sev_bot/.env.example+++ b/examples/agents_api/apps/sev_bot/.env.example@@ -1,4 +1,5 @@OPENAI_API_KEY=sk-...+OPENAI_EXECUTOR_API_KEY=sk-...OPENAI_WEBHOOK_SECRET=SLACK_BOT_TOKEN=xoxb-...SLACK_SIGNING_SECRET=...diff --git a/examples/agents_api/apps/sev_bot/README.md b/examples/agents_api/apps/sev_bot/README.mdindex 4b9e2d0a..20f903eb 100644--- a/examples/agents_api/apps/sev_bot/README.md+++ b/examples/agents_api/apps/sev_bot/README.md@@ -33,7 +33,7 @@ sequenceDiagram- Python 3.14+ and `uv`.- A sandbox: self-hosted Docker or a [third-party provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).-- An OpenAI API key.+- An OpenAI API key and a separate restricted executor key.- A Slack app installed in `#oncall`, with a bot token, signing secret, and message event subscriptions.- PagerDuty, incident.io, or an Alertmanager-compatible monitoring system.- Read access to the affected GitHub repository.@@ -52,11 +52,13 @@ docker build -t agent-api-sev-sandbox:latest examples/agents_api/apps/sev_botCreate the Slack app from [`slack-app-manifest.yaml`](slack-app-manifest.yaml). Replace `https://your-app.example` with your application's HTTPS address, install the app, and invite it to `#oncall`.-Add `OPENAI_API_KEY`, `SLACK_BOT_TOKEN`, and `SLACK_SIGNING_SECRET` to `examples/agents_api/apps/sev_bot/.env`.+Add `OPENAI_API_KEY`, `OPENAI_EXECUTOR_API_KEY`, `SLACK_BOT_TOKEN`, and `SLACK_SIGNING_SECRET` to `examples/agents_api/apps/sev_bot/.env`. Use OpenAI keys with the same owner, organization, and project.The manifest subscribes to `message.channels` and `message.groups` at `/slack/events`, and sends approval actions to `/slack/actions`. Slack must be able to reach both URLs over HTTPS. Posting the initial investigation only needs the bot token; follow-ups and approval buttons also require these callbacks.-Each incident gets a self-hosted sandbox running `codex exec-server`. The app passes your OpenAI API key as `CODEX_API_KEY` at runtime; it does not copy Slack, GitHub, or AWS credentials into the sandbox. Follow-ups reuse the sandbox, and resolution or application shutdown deletes it.+Each incident gets a self-hosted sandbox running `codex exec-server`. The app passes only `OPENAI_EXECUTOR_API_KEY` as `CODEX_API_KEY`; the application, Slack, GitHub, and AWS credentials stay outside the sandbox. The executor key needs `api.agents.environments.connect` and IP restrictions that allow the sandbox's outbound network. Follow-ups reuse the sandbox, and resolution or application shutdown deletes it.++To create an executor key with the required permission, open [Agents > Environments > Keys](https://platform.openai.com/agents?tab=environments&environment_view=keys) and select **Create**.The app mounts [`runbooks/`](runbooks/) read-only at `/workspace/runbooks`. The agent reads `checkout-api.md` for mitigation steps and recovery checks. Add a runbook named after each service when connecting your own incidents.@@ -64,7 +66,7 @@ The app mounts [`runbooks/`](runbooks/) read-only at `/workspace/runbooks`. TheIn [Project settings > Webhooks](https://platform.openai.com/settings/project/webhooks), register `https://your-app.example/webhooks/openai`, subscribe to `agent.session.action_required`, and add its signing secret as `OPENAI_WEBHOOK_SECRET` in `.env`.-With all four credentials configured, start the receiver:+With these credentials configured, start the receiver:```bashuv run examples/agents_api/apps/sev_bot/main.pydiff --git a/examples/agents_api/apps/sev_bot/agent.py b/examples/agents_api/apps/sev_bot/agent.pyindex 024d8a6e..b9b212d3 100644--- a/examples/agents_api/apps/sev_bot/agent.py+++ b/examples/agents_api/apps/sev_bot/agent.py@@ -6,6 +6,7 @@ import asyncioimport jsonimport loggingimport os+import sysfrom collections.abc import AsyncIteratorfrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime@@ -14,7 +15,7 @@ from typing import Anyimport dockerfrom docker.models.containers import Container-from openai import AsyncOpenAI+from openai import AsyncOpenAI, NotFoundErrorfrom openai.lib.streaming.agents import AsyncToolHandlerfrom openai.types.beta import AgentSessionEventfrom openai.types.beta.agents.session_create_params import Agent@@ -47,7 +48,7 @@ def start_executor(environment_id: str, remote_url: str) -> Container:"--environment-id",environment_id,],- environment={"CODEX_API_KEY": os.environ["OPENAI_API_KEY"]},+ environment={"CODEX_API_KEY": os.environ["OPENAI_EXECUTOR_API_KEY"]},volumes={str(EXAMPLE_DIR / "runbooks"): {"bind": "/workspace/runbooks", "mode": "ro"}},@@ -537,21 +538,39 @@ If a rollout caused the incident, propose a rollback to the previous healthy verincident.record("Closed the incident session and sandbox.")async def close_runtime(self, incident: Incident) -> None:- try:- if (- incident.session_id is not None- and incident.session_id not in self.closed_sessions- ):- await self.client.beta.agents.sessions.delete(incident.session_id)- self.closed_sessions.add(incident.session_id)+ original_error = sys.exception()+ session_id = incident.session_id+ errors: list[Exception] = []+ if session_id is not None and session_id not in self.closed_sessions:+ try:+ await self.client.beta.agents.sessions.delete(session_id)+ except NotFoundError:+ self.closed_sessions.add(session_id)incident.session_id = None- finally:- if incident.sandbox is not None:+ except Exception as error:+ errors.append(error)+ else:+ self.closed_sessions.add(session_id)+ incident.session_id = None+ if incident.sandbox is not None:+ try:await asyncio.to_thread(incident.sandbox.remove, force=True)+ except docker.errors.NotFound:+ incident.sandbox = None+ except Exception as error:+ errors.append(error)+ else:logger.info("%s: removed sandbox %s", incident.id, incident.sandbox.short_id)incident.sandbox = None+ if original_error is not None:+ for error in errors:+ original_error.add_note(f"Cleanup for session {session_id}: {error}")+ elif errors:+ raise ExceptionGroup(+ f"Could not clean up session {session_id} and its sandbox", errors+ )async def close(self) -> None:errors: list[Exception] = []diff --git a/examples/agents_api/apps/slack_bot/.env.example b/examples/agents_api/apps/slack_bot/.env.exampleindex e0308450..c5522457 100644--- a/examples/agents_api/apps/slack_bot/.env.example+++ b/examples/agents_api/apps/slack_bot/.env.example@@ -1,4 +1,5 @@OPENAI_API_KEY=sk-...+OPENAI_EXECUTOR_API_KEY=sk-...SLACK_BOT_TOKEN=xoxb-...SLACK_APP_TOKEN=xapp-...diff --git a/examples/agents_api/apps/slack_bot/README.md b/examples/agents_api/apps/slack_bot/README.mdindex a7b7f4d5..a12728aa 100644--- a/examples/agents_api/apps/slack_bot/README.md+++ b/examples/agents_api/apps/slack_bot/README.md@@ -24,7 +24,7 @@ sequenceDiagram- Python 3.14+ and `uv`.- A sandbox: self-hosted Docker or a [third-party provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).-- An OpenAI API key.+- An OpenAI API key and a separate restricted executor key.- A Slack workspace where you can install an internal application.## 1. Build the sandbox image@@ -36,7 +36,9 @@ cp examples/agents_api/apps/slack_bot/.env.example examples/agents_api/apps/slacdocker build -t agent-api-sandbox:latest examples/agents_api/sandboxes/application_managed/docker```-Add your OpenAI API key to `examples/agents_api/apps/slack_bot/.env`. The application loads this file automatically.+Set `OPENAI_API_KEY` and `OPENAI_EXECUTOR_API_KEY` in `examples/agents_api/apps/slack_bot/.env`. Use keys with the same owner, organization, and project. Only the executor key enters the sandbox. It needs `api.agents.environments.connect` and IP restrictions that allow the sandbox's outbound network. The application loads this file automatically.++To create an executor key with the required permission, open [Agents > Environments > Keys](https://platform.openai.com/agents?tab=environments&environment_view=keys) and select **Create**.For production, you can replace Docker with a hosted [sandbox provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).diff --git a/examples/agents_api/apps/slack_bot/agent.py b/examples/agents_api/apps/slack_bot/agent.pyindex 7ee119a2..ba5736ab 100644--- a/examples/agents_api/apps/slack_bot/agent.py+++ b/examples/agents_api/apps/slack_bot/agent.py@@ -4,11 +4,12 @@ from __future__ import annotationsimport asyncioimport os+import sysfrom collections.abc import AsyncIterator, Awaitable, Callableimport dockerfrom docker.models.containers import Container-from openai import AsyncOpenAI+from openai import AsyncOpenAI, NotFoundErrorfrom openai.types.beta import AgentSessionEventfrom openai.types.beta.agents.session_create_params import Agentfrom slack_sdk.web.async_client import AsyncWebClient@@ -39,7 +40,7 @@ def start_executor(environment_id: str, remote_url: str) -> Container:"--environment-id",environment_id,],- environment={"CODEX_API_KEY": os.environ["OPENAI_API_KEY"]},+ environment={"CODEX_API_KEY": os.environ["OPENAI_EXECUTOR_API_KEY"]},detach=True,auto_remove=True,init=True,@@ -111,8 +112,13 @@ class SlackBot:sandbox = await asyncio.to_thread(start_executor, environment.id, environment.remote_url)- except BaseException:- await self.client.beta.agents.sessions.delete(session.id)+ except BaseException as original_error:+ try:+ await self.client.beta.agents.sessions.delete(session.id)+ except Exception as cleanup_error:+ original_error.add_note(+ f"Could not delete session {session.id}: {cleanup_error}"+ )raiseself.sessions[thread_id] = session.id@@ -200,17 +206,37 @@ class SlackBot:)async def close(self) -> None:+ original_error = sys.exception()errors: list[Exception] = []for thread_id, session_id in self.sessions.items():try:await self.client.beta.agents.sessions.delete(session_id)+ except NotFoundError:+ passexcept Exception as error:+ error.add_note(f"Could not delete session {session_id}.")+ if original_error is not None:+ original_error.add_note(+ f"Could not delete session {session_id}: {error}"+ )errors.append(error)sandbox = self.sandboxes.get(thread_id)if sandbox is not None:try:- await asyncio.to_thread(sandbox.stop)+ await asyncio.to_thread(sandbox.remove, force=True)+ except docker.errors.NotFound:+ passexcept Exception as error:+ error.add_note(+ f"Could not remove sandbox for session {session_id}."+ )+ if original_error is not None:+ original_error.add_note(+ f"Could not remove sandbox for session {session_id}: {error}"+ )errors.append(error)- if errors:+ if errors and original_error is None:raise ExceptionGroup("Could not close all Slack runtimes", errors)+ if not errors:+ self.sessions.clear()+ self.sandboxes.clear()